如何在使用 javaassist 创建类时将 @Override
注解添加到方法中?
ClassPool pool = ClassPool.getDefault();
CtClass ctClasz = pool.makeClass("test.ExampleImpl");
ctClasz.addInterface(pool.get(MyInterface.class.getName()));
CtMethod method = CtNewMethod.make ("@Override public void print() { System.out.println(\"Hello! \"); }", ctClasz);
ctClasz.addMethod(method);
System.out.println("Implementd: Interfaces:" + ctClasz.getInterfaces());
System.out.println("Methods: " + ctClasz.getMethods());
ctClasz.writeFile("D:");
这段代码抛出如下异常:
Exception in thread "main" javassist.CannotCompileException: [source error] syntax error
near "@Override p"
at javassist.CtNewMethod.make(CtNewMethod.java:78)
at javassist.CtNewMethod.make(CtNewMethod.java:44)
at javaassist.Demo.main(Demo.java:17)
Caused by: compile error: syntax error near "@Override p"
at javassist.compiler.Parser.parseClassType(Parser.java:983)
at javassist.compiler.Parser.parseFormalType(Parser.java:191)
at javassist.compiler.Parser.parseMember1(Parser.java:51)
at javassist.compiler.Javac.compile(Javac.java:89)
at javassist.CtNewMethod.make(CtNewMethod.java:73)
... 2 more
最佳答案
@Override
不是运行时注解,因此即使您可以添加它,也不会产生任何影响。
对于确实具有运行时效果的注释 (RetentionPolicy.RUNTIME
),您可以查看 this question .
关于java - 如何在使用 javaassist 创建 .class 文件时向方法添加 @Override 注释?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11313114/