如何@Override使用javaassist创建类时向方法添加注释?
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:");
Run Code Online (Sandbox Code Playgroud)
此代码抛出异常如下:
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
Run Code Online (Sandbox Code Playgroud) 可能重复:
我们可以覆盖Java中的静态方法吗?
我们不能覆盖基类的静态方法.
其实我试过这样的事情:
// Base class
public class StaticExampleImpl {
protected String name="overriding";
public static void display(){
System.out.println("static method display : base class");
}
}
Run Code Online (Sandbox Code Playgroud)
然后派生类如下:
//derived class
public class StaticDemo extends StaticExampleImpl {
// cannot override the static methods...
//@Override
public static void display(){
System.out.println("child!!! static method display");
}
public static void main(String[] args) {
StaticDemo d=new StaticDemo();
d.display(); // derived class display is called rather than Base class.
}
}
Run Code Online (Sandbox Code Playgroud)
因此,当我取消注释该@Override方法时,它会给出错误,因为"静态方法无法覆盖".但通过评论,它运作正常.因此,当我们创建Objects并使用实例调用静态方法时,这些工作正常.那么区别是什么呢??