Java library architecture

1) There is Somelib that is added as a jar in SomeProject .

2) SomeProject has somePackage.SomeClass that implements SomeLib.SomeInterface .

3) SomeLib should be able to instantiate somePackage.SomeClass without creating SomeLib every time

How is this possible without the use of reflection? It is not possible to write to SomeLib something like import somePackage.Someclass.

I am using Netbeans.

PS I am new to Java and I tried to be as clear as possible.

+3
source share
3 answers

You can simply add a hard-coded dependency, but you should avoid this at all costs if you plan to reuse your library (and even if you don't)

Use this template instead:

  • Create a factory to create implementations SomeInterfacein your library. (For details, see Factory Method Template )

  • In SomeProjectyou need to register SomeClassusing factory. You can use a static initializer in conjunction with Class.forNamefor this.

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

    , . Class.forName: SomeClass . , , .

  • SomeLib factory SomeInterface.

    SomeInterface si = SomeFactory.createSomeObject();
    
+3

:

Class.forName("com.bla.yourclass").newInstance();
+1

, ( java-, xml) . , . , .

, .

0
source

Source: https://habr.com/ru/post/1718781/


All Articles