I am using Javassist to generate some classes at runtime and when I make anonymous inner classes in these classes they crash upon trying to instantiate an enclosing object (as far as I can tell)
I have tried to implement the simplest version of what I am trying to do.
I define 3 classes as follows:
public class A {
public int method() {
return 1;
}
}
public class B extends A {
}
public class C extends A {
public int method() {
return 5;
}
}
What I want to do now is use javassist (or something else I guess) to (at runtime) generate a class that has all of the functionality of C but that extends B instead of A, to me this seems like a thing that would be fine, since B extends A. Currently I am doing this as follows:
ClassPool cp = ClassPool.getDefault();
CtClass cc = cp.get(C.class.getName());
cc.setName("newName");
cc.setSuperclass(cp.get(B.class.getName()));
B b = (B) cc.toClass().newInstance();
b.method();
The above code works fine when I call method(), but If I instantiate an anonymous inner class in C's method() like this:
public class C extends A {
public int method() {
try {
return new Callable<Integer>() {
@Override
public Integer call() throws Exception {
return 5;
}
}.call();
} catch (Exception e) {
return 2;
}
}
}
when I call method()
I get java.lang.NoSuchMethodError: C$1.<init>(LnewName;)
error.
While I would love for someone to tell me differently I think this may not be possible with Javassist, I found the following line in section 4.7 of the Javassist tutorial:
"Inner classes or anonymous classes are not supported."
So I guess I should look into other runtime class generation libraries
Javassist doesn't support non-static inner classes.
See javadoc for method CtClass.makeNestedClass(String nestedClassName,boolean isStatic)
.
Your problem can't be resolved unless you move to top-level your anon inner class.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.