javassist を使用して、インターフェイスを実装するクラスを (実行時に) プログラムで作成およびコンパイルしようとしています。
その動的クラスのインスタンスを呼び出すたびに、次のエラーが発生します。
java.lang.AbstractMethodError: FooImpl.test()Ljava/lang/Object;
これが私のインターフェースです
public class FooBarInterface<T> {
public T getEntity();
}
これがエンティティのサンプルです
public class FooEntity {
@Override
public String toString() {
return "Hello, Foo!";
}
}
インターフェイスをプログラムで実装する方法は次のとおりです
public void test() {
ClassPool classPool = ClassPool.getDefault();
CtClass testInterface = classPool.get(FooBarInterface.class.getName());
CtClass fooImpl = classPool.makeClass("FooImpl");
fooImpl.addInterface(testInterface);
CtMethod testMethod = CtNewMethod.make(
"public com.test.FooEntity getEntity(){" +
"return new com.test.FooEntity();" +
"}",
canImpl
);
fooImpl.addMethod(testMethod);
fooImpl.writeFile();
TestInterface<FooEntity> test =
(TestInterface<FooEntity>) fooImpl.toClass().newInstance();
System.out.println(test.getEntity());
}
実装されたメソッドの戻り値の型を Object に変更した場合、次のようにエラーは発生しません。
CtMethod testMethod = CtNewMethod.make(
"public Object getEntity(){" +
"return new com.test.FooEntity();" +
"}",
canImpl
);
その後、私は正常に取得しhello, Foo!
ます。戻り値の型を Object に変更しても問題ありませんが、 Foo 型で返すと が生成される理由をもっと理解したいと思いますAbstractMethodError
。