How to add the @Override
annotation to a method while creating the 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 is throwing 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
@Override @Override annotation informs the compiler that the element is meant to override an element declared in a superclass. Overriding methods will be discussed in Interfaces and Inheritance. While it is not required to use this annotation when overriding a method, it helps to prevent errors.
The @Override annotation is one of a default Java annotation and it can be introduced in Java 1.5 Version. The @Override annotation indicates that the child class method is over-writing its base class method. It extracts a warning from the compiler if the annotated method doesn't actually override anything.
The annotation @Override is used for helping to check whether the developer what to override the correct method in the parent class or interface.
@Override annotation is used when we override a method in sub class. Generally novice developers overlook this feature as it is not mandatory to use this annotation while overriding the method.
The @Override annotation denotes that the child class method overrides the base class method. For two reasons, the @Override annotation is useful. If the annotated method does not actually override anything, the compiler issues a warning. It can help to make the source code more readable.
@Override
isn't a runtime annotation so even if you could add it, it wouldn't make any difference whatsoever.
For annotations that do have a runtime effect (RetentionPolicy.RUNTIME
), you can take a look at this question.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With