Search code examples
javatomcatclassloaderclassnotfoundexceptionclasscastexception

Load a class from a JAR implementing interface existing in my project's source code


One of my web application's module has a GeneralOperation interface that I want other users to implement in order to provide their own functionality.

I create a JAR of the module that contains this interface, and provide it to users. Then, a user can import this library and create a class MyCustomOperationimplementing this interface. Finally, they generate a JAR that contains their implementation, and they drop their JAR in the tomcat/lib folder, so that JVM can see that during runtime.

Back to my application when I try to load their MyCustomOperation class, it fails to be casted to the GeneralOperation interface existing in the source code, because it thinks that the GeneralOperation that the MyCustomOperation implements, is a difference interface, and not the existing one.

How to resolve this?


Solution

  • A class is identified by its name and its class loader. your implementation MyCustomOperation is loaded by tomcat common class loader and Interface GeneralOperation is loaded by tomcat Webapp class loader. Therefore you cannot cast between these two types.

    To solve your issue,

    1.you can use Serialization

    2.or take you Interface in to tomcat common classloder(tomcal/lib) and implementation into webapp( this way you can load the class without reflection).