How to use an implementation loaded with a different Java class loader?

I am writing a library where I allow people to provide implementations of certain interfaces using the plugin framework (this is JPF if you are familiar). Plugins are not saved on the way to classes. The structure gives me a ClassLoader for each plugin, so when I ask for an implementation with the MyImpl interface name "MyInterface", I can find the correct plugin and then use this ClassLoader plugin to load the class from which I can create an instance if I know something about constructor. So far so good.

However, I now have a case where I need to call a method available only for this particular implementation. So, I can try to do this in two ways:

Method 1:

// Makes sure that MyImpl has been loaded, using the custom classloader
Plugins.getClass(MyInterface.class, "MyImpl");
// This line will not compile because MyImpl is not available at build time
MyImpl foo = new MyImpl();
// If I could get this far, this line would work:
foo.methodOnlyInMyImpl();

Method 2:

// This call will get an instance of MyImpl (already written and tested)
MyInterface foo = Plugins.getInstance(MyInterface.class, "MyImpl");
// Compiler error because there is no MyInterface.methodOnlyInMyImpl method.
foo.methodOnlyInMyImpl()

1 - , , , "" . .

, :
A. 2, methodOnlyInMyImpl (, !)
B. , 1, . ( )
C. B +, , , , ( )

, :

  • , ?
  • B, ? , , MyImpl, , . , MyImpl foo, MyImpl , ( Plugins.newInstance MyImpl)?
+3
2

-, , ? , .

JPF, Java . :

  • , , , . 2 , .

  • . . - -.

+3
+2

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


All Articles