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.
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:
Create a factory for creating
SomeInterfaceimplementations in your library. (See Factory method pattern for more information)In
SomeProjectyou have to register yourSomeClasswith that factory. You can use a static initializer in conjuction withClass.forNamefor that.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 aSomeClassinstance in the library. But here you use it in the project for loading the class and thus running the static initializer.SomeLibthen can use the factory to create an instance forSomeInterface.