java javassist.CannotCompileException: by java.lang.LinkageError: loader

java javassist.CannotCompileException: by java.lang.LinkageError: loader

我需要在不重新编译应用程序的情况下更改方法(计算公式)。我知道这可以在 javassist 的帮助下完成。到目前为止,我正在尝试一个简单的例子。在post方法中,我调用了createMethodHelper()方法,必须要改Helper2方法。一切都好。但是经过多次调用(重新加载页面),报错 javassist.CannotCompileException: by java.lang.LinkageError: loader 因此,class 包含我想要更改的唯一方法

package ru.testScandJavaCafee.controller;

public class Helper2 {
public String createList()
    {
        System.out.println("++++");
        return "1000";
    }
}

以及我从中更改方法的class

public String createMethodHelper() throws NotFoundException, CannotCompileException, NoSuchMethodException, InvocationTargetException, IllegalAccessException, IOException, InstantiationException, ClassNotFoundException {

        ClassPool pool = ClassPool.getDefault();
pool.insertClassPath(new ClassClassPath(this.getClass()));
        CtClass cc = pool.get("ru.testScandJavaCafee.controller.Helper2");
        cc.defrost();
        CtMethod cm = cc.getMethod("createList","()Ljava/lang/String;" );
        cc.defrost();
        cm.setBody( "{  return \"300 \" ;}" );

        cc.defrost();
        Class c = cc.toClass();
        cc.defrost();
ru.testScandJavaCafee.controller.Helper2 test = (ru.testScandJavaCafee.controller.Helper2) c.newInstance();
        String sum = test.createList();

        return sum;
    }

第二次调用(重新加载页面)后,报错

javassist.CannotCompileException: by java.lang.LinkageError: loader (instance of  org/apache/catalina/loader/WebappClassLoader): attempted  duplicate class definition for name: "ru/testScandJavaCafee/controller/Helper2"
    at javassist.ClassPool.toClass(ClassPool.java:1085)
    at javassist.ClassPool.toClass(ClassPool.java:1028)
    at javassist.ClassPool.toClass(ClassPool.java:986)
    at javassist.CtClass.toClass(CtClass.java:1110)
    at ru.testScandJavaCafee.controller.CoffeeTypeController.createMethodHelper(CoffeeTypeController.java:108)
    at ru.testScandJavaCafee.controller.CoffeeTypeController.doPost(CoffeeTypeController.java:56)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:650)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:218)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:110)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:506)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:962)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:452)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1087)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:637)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:318)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.LinkageError: loader (instance of  org/apache/catalina/loader/WebappClassLoader): attempted  duplicate class definition for name: "ru/testScandJavaCafee/controller/Helper2"
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:763)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:642)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at javassist.ClassPool.toClass2(ClassPool.java:1098)
    at javassist.ClassPool.toClass(ClassPool.java:1079)
    ... 27 more

帮助了解如何修复错误

我从 documentation and this tutorial 对此进行了一些研究。而如果你想多次修改方法,你可以这样做:

public static void main(String[] args) {
    try {
        // get a new instance of version 1
        Object newClassInstance1 = m2("com.tima.Helper2", "public String createList() { System.out.println(\"++++\"); return \"200\";}");
        Method method1 = newClassInstance1.getClass().getMethod("createList");

        // this executes the createList in the new class com.tima.Helper2
        String sum1 = (String) method1.invoke(newClassInstance1);
        System.out.println("com.tima.Helper2: " + sum1);

        // this shows that the original Helper method was not modified
        Helper h = new Helper();
        System.out.println("com.tima.Helper: " + h.createList());

        // this shows that the com.tima.Helper2 overrides Helper and can be used as Helper with a modified method
        Helper h2 = (Helper) newClassInstance1;
        System.out.println("com.tima.Helper2 as Helper: " + h2.createList());

        // below does the same thing a second time

        Object newClassInstance2 = m2("com.tima.Helper3", "public String createList() { System.out.println(\"++++\"); return \"300\";}");
        Method method2 = newClassInstance2.getClass().getMethod("createList");
        String sum2 = (String) method2.invoke(newClassInstance2);
        System.out.println("com.tima.Helper3: " + sum2);

        Helper h3 = new Helper();
        System.out.println("com.tima.Helper: " + h3.createList());

        Helper h4 = (Helper) newClassInstance2;
        System.out.println("com.tima.Helper3 as Helper: " + h4.createList());
    } catch (Exception e) {
        e.printStackTrace();
    }
}

public static Object m2(String className, String methodBody) 
        throws CannotCompileException, InstantiationException, IllegalAccessException, NotFoundException {
    // get the pool
    ClassPool classPool = ClassPool.getDefault();

    // this seems optional, but if it isn't Main.class (my test class) should be replaced with this.getClass()
    classPool.insertClassPath(new ClassClassPath(Main.class));

    // get the helper class
    CtClass helperClass = classPool.get("com.tima.Helper");

    // create a new class
    CtClass newCtClass = classPool.makeClass(className);

    // make it  child of Helper
    newCtClass.setSuperclass(helperClass);

    // this overrides the method in Helper
    newCtClass.addMethod(CtNewMethod.make(methodBody, newCtClass));

    // get a new instance
    Class<?> newClass = newCtClass.toClass();
    Object newClassInstance = newClass.newInstance();

    return newClassInstance;
}

输出

++++
com.tima.Helper2: 200
++++
com.tima.Helper: 1000
++++
com.tima.Helper2 as Helper: 200
++++
com.tima.Helper3: 300
++++
com.tima.Helper: 1000
++++
com.tima.Helper3 as Helper: 300

基本上,每次调用该方法时,它都会创建一个新的 class,使 Helper class 成为它的超级 class 并覆盖 createList 方法.这里的明显问题取决于调用此方法的次数,最终会生成大量 classes。因此,您可能希望在创建之前添加检查这些 class 是否已加载。

你说这个方法 运行s 当你刷新/加载页面时所以如果你只希望它 运行 一次,我建议你把这个代码放在一个单例中 运行s 当您的应用程序启动时。我不确定您在 Web 应用程序中使用的是什么,但是 JSF 和 Spring 都有用于此类用途的单例 bean。