How to add @Override annotation to a method when creating a .class file using javaassist?

How to add annotation @Overrideto a method when creating a class using 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:");

This code throws an exception as follows:

 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
+5
source share
3 answers

@Override is not a run-time annotation, so even if you can add it, it will not change anything.

For annotations that have a runtime effect ( RetentionPolicy.RUNTIME), you can look at this question .

+7
source

Short version

Not interesting to add annotation. Because, as it has this @java.lang.annotation.Retention(value=java.lang.annotation.RetentionPolicy.SOURCE), it will not make any difference. Therefore, you do not need to worry about this problem.

, @java.lang.annotation.Retention(value=java.lang.annotation.RetentionPolicy.RUNTIME).

@java.lang.annotation.Retention(value=java.lang.annotation.RetentionPolicy.SOURCE) , , JAVASSIST, .

. Java , . JAVASSIST , .

:

  • CLASS , VM .
  • RUNTIME VM , .
  • SOURCE .

JAVASSIST RUNTIME CLASS ( CLASS , . ).

+3

@Override .

, , :

a. Overrides a method on the superclass
b. Implements an interface method.

. , , , , , .

, @Override .

Edit

:

public interface Foo {
    void bar();
}

public class FooImpl {
    public void bar() { ... }
}

public class MyFooExtension extends FooImpl {
    public void bar() { .... }
}

Foo FooImpl:

public interface Foo {
    void bar(String input);
}

public class FooImpl {
    public void bar(String input) { ... }
}

The MyFooExtension class will still compile, but the "bar ()" method in this class will never be called. So your method is useless. If you add the @Override annotation, you will get a compilation error telling you that no "void bar ()" method is being overridden, and you will need to fix your class in order to compile it.

+2
source

All Articles