Thread.currentThread().setContextClassLoader without using reflection
I have a "com.test.Test1" class which is in test.jar. I use this jar for compiling but does not deploy with my webapp. I want my servlet loading this jar dynamically during runtime.
Is there any way to load the classes dynamically without using Java reflection? the reason why I ask this is because I don't want to convert tons of my existing code to java reflection.
public class servlet1 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException {
URLClassLoader urlClassLoader = new URLClassLoader(new URL[] { new File("test.jar").toURI().toUR开发者_如何学JAVAL() }, null);
Thread.currentThread().setContextClassLoader(urlClassLoader);
Class c = newClassLoader.loadClass("com.test.Test1");
//////
Test1 test1 = new Test1() ==> ClassNotFound Exception
test1.testMeothod();
///////
// if using java reflection will work
c.newInstance() ...........
Method m = c.getDeclaredMethod("startup", null);
.....
.....
//////
}
}
You can load classes that way, but you can't name them in the code. You have to refer to them via some base class or interface that they extend/implement that is present in the classapath. You don't have to use Reflection if the class has a default constructor, just Class.newInstance()
.
You can refactor your code to pull out the interface of Test1 . So you can use your interface directly without reflection. Interface is recommended, due to using abstract class will cause some trouble when loading subclass in other classloader.
You can find the trouble here.
ClassCircularityError is thrown when getCanonicalName
精彩评论