Search code examples
javaplayframeworkautoloader

PHP like Autoloader in Java


Does the Java Interpreter support an Autoloader-Function or a possibility to extend his "Looking for a class"-function?

In PHP there is a function called spl_autoload_register (see http://www.php.net/manual/en/function.spl-autoload-register.php for details ), which forces the interpreter to execute my own callback function when he is looking for a missing class. In my callback function I can include the file with the expected class.

The background-idea is that I'd like to switch dynamically between software-layers.

For example:
If class x_L2 exists in layer 2 then class x_L1 in the underlying layer 1 should be ignored. Actually I solved this issue with a general mirror class x, which have to inherit from the class in the highest available layer. But this way is error-prone when you have to maintain hundreds of classes.

Thanks in advance.


Solution

  • Classes are identified by their package, as classes can be identified by namespaces in PHP. In order to use a specific class, you can simply use a qualified name.

    public mypackage.mysubpackage.Myclass myInstanceofMyClass;

    Or you could import only the needed class :

    import mypackage.mysubpackage.Myclass;

    You cannot have a class having the same name as another class in the same package. That's a duplicate définition of a type. I am not aware of a callback function for inclusion.