[英]Javassist: Create class that implements generic interface
I´m trying to create a class with javassit that implements a generic interface passing the generic argument but without sucess so far. 我正在尝试使用javassit创建一个类,该类实现了传递通用参数但到目前为止没有成功的通用接口。
I´m aware of the answer Javassist: creating an interface that extends another interface with generics and the javassit tutorial but none of those helped. 我知道Javassist的答案:创建一个接口,该接口使用泛型和javassit教程 扩展了另一个接口,但是这些都不起作用 。
Here is my code: 这是我的代码:
String met = "public void doit(com.package.Pojo o) { System.out.println(\"Result: \" + o.getName()); }";
ClassPool cp = ClassPool.getDefault();
CtClass cc = cp.makeClass("Teste");
cc.setInterfaces(new CtClass[]{cp.get("com.package.Factor")});
ClassSignature cs = new ClassSignature(null, null,
// Set interface and its generic params
new ClassType[]{new ClassType("com.package.Factor",
new TypeArgument[]{new TypeArgument(new ClassType("com.package.Pojo"))}
)});
cc.setGenericSignature(cs.encode());
//cc.setGenericSignature("Ljava/lang/Object;Lcom/aurora/core/util/Factor<Lcom/aurora/core/util/Pojo;>;");
CtMethod make = CtNewMethod.make(met, cc);
cc.addMethod(make);
Class<Factor<Pojo>> class1 = cc.toClass();
Factor<Pojo> obj = (Factor<Pojo>) class1.newInstance();
obj.doit(new Pojo("name here"));
Factor class: 要素类:
public interface Factor<T> {
void doit(T ent);
}
My pom 我的绒球
<dependency>
<groupId>org.javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.20.0-GA</version>
</dependency>
And the error: 错误:
Exception in thread "main" java.lang.AbstractMethodError: Teste.doit(Ljava/lang/Object;)V at com.package.Main3.main(Main3.java:40)
线程“主”中的异常java.lang.AbstractMethodError:com.package.Main3.main(Main3.java:40)的Teste.doit(Ljava / lang / Object;)V
Thanks in advance ! 提前致谢 !
The Java runtime works with type erasure. Java运行时可用于类型擦除。 Therefore, the
doit(T)
method is defined as doit(java.lang.Object)
in the interface type. 因此,
doit(T)
方法在接口类型中定义为doit(java.lang.Object)
。 In order to override a method, you need to implement it in the generated class. 为了覆盖一个方法,您需要在生成的类中实现它。 The Java compiler does this for you transparently when you define a method, javassist does not do it for you.
Java编译器在定义方法时会透明地为您执行此操作,而javassist不会为您执行此操作。
Therefore, you need to add a so-called bridge method that invokes the actual method but that overrides the interface's method: 因此,您需要添加一个所谓的桥接方法 ,该方法调用实际方法,但该方法覆盖接口的方法:
public void doit(Object ent) {
doit((Pojo) ent);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.