Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/308.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Thread.currentThread().setContextClassLoader不使用反射_Java - Fatal编程技术网

Java Thread.currentThread().setContextClassLoader不使用反射

Java Thread.currentThread().setContextClassLoader不使用反射,java,Java,我在test.jar中有一个“com.test.Test1”类。我使用这个jar进行编译,但不与我的webapp一起部署。我希望servlet在运行时动态加载这个jar 是否有任何方法可以在不使用Java反射的情况下动态加载类?我之所以问这个问题,是因为我不想将大量现有代码转换为java反射 public class servlet1 extends HttpServlet { protected void doPost(HttpServletRequest request, Http

我在test.jar中有一个“com.test.Test1”类。我使用这个jar进行编译,但不与我的webapp一起部署。我希望servlet在运行时动态加载这个jar

是否有任何方法可以在不使用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);
        .....
        .....
        //////    
    }
}

可以这样加载类,但不能在代码中命名它们。您必须通过一些基类或接口来引用它们,这些基类或接口是它们扩展/实现的,这些基类或接口存在于classapath中。如果类具有默认构造函数,则不必使用反射,只要
class.newInstance()

您可以重构代码以拉出Test1的接口。 因此,您可以直接使用界面而无需进行反射。 建议使用接口,因为使用抽象类会导致 在其他类加载器中加载子类时出现一些问题

你可以在这里找到麻烦


抽象基类必须由加载using类的类加载器加载,例如OP发布的代码。你的链接不适用。抱歉,我不明白。我只是说最好的做法是使用接口作为存根。我建议避免使用
Class.newInstance
,因为它是邪恶的。将船推出,并罚款
构造函数
@Clark Bao使用
Class.getConstructor
获得
构造函数
。使用
构造函数调用.newInstance
。这可以防止任何已检查的异常直接通过未检查。