views:

67

answers:

3

1) There is Somelib which is added as jar in SomeProject.

2) In SomeProject there is the somePackage.SomeClass which implements SomeLib.SomeInterface.

3) SomeLib must be able to create somePackage.SomeClass instance without building SomeLib each time

How is it possible without using reflection? It's impossible to write in SomeLib something like import somePackage.Someclass.

I'm using Netbeans.

PS I'm newbie to Java and I tried to be as clear as possible.

+1  A: 

you can try to instantiate the class with this:

Class.forName("com.bla.yourclass").newInstance();
clamp
Yes, but in Overdoses case, SomeLib shall not know the names of SomeInterface implementors (loose coupling)
Andreas_D
+2  A: 

You just could add a hard-coded dependency, but you should avoid that at all costs if you are planning to re-use your library (and even if you don't)

Instead use this pattern:

  1. Create a factory for creating SomeInterface implementations in your library. (See Factory method pattern for more information)

  2. In SomeProject you have to register your SomeClass with that factory. You can use a static initializer in conjuction with Class.forName for that.

    public class SomeClass {
        static {
          SomeFactory.registerSomeImplementation(SomeClass.class)
        }
    }
    
    
    Class.forName("somePackage.SomeClass") // Alternative 1 
    SomeClass.class.getName();             // Alternative 2
    

    Both alternatives load the class and run the static initializer, but the second one offers some better refactoring opportunities. Don't be confused with Class.forName: One of the other answers suggested using it for creating a SomeClass instance in the library. But here you use it in the project for loading the class and thus running the static initializer.

  3. SomeLib then can use the factory to create an instance for SomeInterface.

    SomeInterface si = SomeFactory.createSomeObject();
    
DR
you could also use a prototype, depending on the lifecycle
wds
A: 

I'd declare the classes, that implement your interface in a flat file (either java properties or xml) on the classpath. Your library can look for the file, read the class names and create instances. I think, that's a typical approach.

Then you do not need reflection to search the classpath for implementors but just invocation to create instances.

Andreas_D