Embed presentation
Download to read offline
![import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Method;
/**
* write a program to create a single-value annotation that stores only one value and
* retrieve it during runtime by the JVM
*
*
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@interface MySingle{
int value();
}
class MyClass{
@MySingle(value = 100)
public void myMethod(){
System.out.println("Hello");
}
}
public class Demo {
public static void main(String[] args) throws NoSuchMethodException,
SecurityException {
MyClass obj = new MyClass();
Method m = obj.getClass().getMethod("myMethod");
MySingle anno = m.getAnnotation(MySingle.class);
System.out.println("Value = "+anno.value());
}
}
output :
Value = 100](https://image.slidesharecdn.com/onetrillionjavaprogramchallenge-160829014944/85/single-value-annotation-1-320.jpg)

This Java code defines a single-value annotation called MySingle that stores an integer value. It creates a MyClass with a myMethod annotated with MySingle and sets the value to 100. The main method retrieves the MyMethod at runtime, gets the MySingle annotation on it, and prints out the value, displaying 100.
![import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Method;
/**
* write a program to create a single-value annotation that stores only one value and
* retrieve it during runtime by the JVM
*
*
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@interface MySingle{
int value();
}
class MyClass{
@MySingle(value = 100)
public void myMethod(){
System.out.println("Hello");
}
}
public class Demo {
public static void main(String[] args) throws NoSuchMethodException,
SecurityException {
MyClass obj = new MyClass();
Method m = obj.getClass().getMethod("myMethod");
MySingle anno = m.getAnnotation(MySingle.class);
System.out.println("Value = "+anno.value());
}
}
output :
Value = 100](https://image.slidesharecdn.com/onetrillionjavaprogramchallenge-160829014944/85/single-value-annotation-1-320.jpg)