简体   繁体   中英

Interface in library, implementations in different apps, method call from library

I have an interface method in a library which is being called by a method in the same library. The implementations are in the applications which include the library. The implementations are different for every application. In order to call the interface method , the calling method must instantiate the interface with its implemented class . But since the calling method is in the library, it has no access to the classes in the applications. The calling method is started by a background service and not by the application.

The interface in the library:

public interface InterfaceA {
    void methodA();
}

The class in the application which implements the interface:

public class ClassA implements InterfaceA {
    @Override
    public void methodA() {
        // do something
    }
}

The method in the library which calls the interface method:

public void callInterface() {
    InterfaceA ia;
    ia.methodA(); // how to get this to work?
}

How do I call the interface method from the library without any access to the interface implementations in the applications? I cannot instantiate the interface from my library as the implementation classes are in the application which the library has no access to.

You don't need to do anything to get it to work if you have an instance of the interface:

public void callInterface(InterfaceA ia) {
    ia.methodA();
}

And then add this parameter to the library methods which call this method, and so on. When applications call this method, they can pass their implementations.

Or if you really need to instantiate the interface inside the method, add another interface:

public void callInterface(Supplier<InterfaceA> iaSupplier) {
    InterfaceA ia = iaSupplier.get();
    ia.methodA();
}

See https://docs.oracle.com/javase/8/docs/api/java/util/function/Supplier.html .

The calling method is started by a background service and not by the application.

And what starts the background service? You need to add some way for the application to pass the implementation to it.

Alternately, you could use SPI ( https://docs.oracle.com/javase/tutorial/ext/basics/spi.html ) but it may be overkill.

public void callInterface() {
    InterfaceA ia;
    ia.methodA(); // how to get this to work?
}

Above should result in compilation problem.

The library function should take as parameter the Interface InterfaceA in method as shown in another answer Or If it is a stateless implementation then pass it while using the Class that contain this method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM