import java.util.*;
class Parent {
void childOf() {
System.out.println("Child of Parent");
}
}
class Child extends Parent {
@Override
void childof() {
System.out.println("Parent");
}
}
public class Annotation {
public static void main(String args[]) {
Parent a = new Child();
a.childOf();
}
}
Output:
/*prog.java:14: error: method does not override or implement a method from a supertype
@Override
^
*/
@Retention: This allows the user to specify, to what level the annotation will be available or till when the annotation will be retained in the program.
RetentionPolicy.SOURCE: will not be available in compiled class and will only be retained till source level.
RetentionPolicy.CLASS: these are retained till compile-time and will be ignored by JVM.
RetentionPolicy.RUNTIME: available during runtime and is available to JVM also.
@Documented: It is used for documenting custom annotation by signalling the JavaDoc tool which compiles it and adds it to the generated document.
@Inherited: This allows the subclasses to inherit the marked annotations by this annotation from the superclass.
@Target(ElementType.METHOD)
@interface Annotation {
int val();
String val2();
}
// this means that this annotation can be only applied to methods.
@interface Annotation{ }
@interface Annotation { int value() default 0; }
@interface Annotation{ int value1(); String value2() }
@
before the interface keyword.File: Test.java
import java.util.*;
import java.lang.annotation.*;
import java.lang.reflect.*;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@interface Annotation {
int val();
}
class Example {
@Annotation(val = 25)
public void sayHello() {
System.out.println("Hello annotation");
}
}
public class Test {
public static void main(String args[]) throws Exception {
Example example = new Example();
Method method = example.getClass().getMethod("sayHello");
Annotation obj = method.getAnnotation(Annotation.class);
System.out.println("Value: " + obj.val());
}
}
Output
$ javac Test.java
$ java Test
Value: 25
Help us improve this content by editing this page on GitHub