我有一个“com.test.Test1”类,它在test.jar中。我使用这个jar进行编译,但没有使用我的webapp进行部署。我希望我的servlet在运行时动态加载这个jar。Thread.currentThread()。setContextClassLoader不使用反射
有什么方法可以在不使用Java反射的情况下动态加载类?我之所以问这个问题是因为我不想将大量现有代码转换为java反射。
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().toURL() }, 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);
.....
.....
//////
}
}
我建议避免'Class.newInstance',因为它是邪恶的。推出船并罚款'构造函数'。 –
@Tom。你有什么建议的细节?想要了解它。 –
@Clark Bao用'Class.getConstructor'获取'Constructor'。用'Constructor.newInstance'调用。这可以防止任何检查的异常直接通过未经检查。 –