2.A] Explain single-member annotations with a program example.
Answer:
A single-member annotation is a special type of annotation that has only one element (also known as a member or attribute). In such annotations, you don’t need to specify the name of the element when you use it, as there is only one element to set. This single element is defined using the special method name value()
.
Example of a Single-Member Annotation:
Let’s create a single-member annotation called MyAnnotation
and use it in a program.
Step 1: Define the Single-Member Annotation
import java.lang.annotation.*; // Define the annotation with a single element @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) @interface MyAnnotation { String value(); // Single-member element }
Explanation:
@Retention(RetentionPolicy.RUNTIME)
: This means the annotation will be available at runtime.@Target(ElementType.METHOD)
: This means the annotation can be applied to methods.- The annotation has a single element
value()
, which returns aString
.
Step 2: Use the Single-Member Annotation in a Program
public class SingleMemberAnnotationExample { // Applying the single-member annotation to a method @MyAnnotation("Hello, this is a single-member annotation!") public void myMethod() { System.out.println("myMethod is executed."); } public static void main(String[] args) throws Exception { SingleMemberAnnotationExample obj = new SingleMemberAnnotationExample(); obj.myMethod(); // Accessing the annotation MyAnnotation annotation = obj.getClass() .getMethod("myMethod") .getAnnotation(MyAnnotation.class); System.out.println("Annotation value: " + annotation.value()); } }
Explanation:
- Annotation Usage:
- The
@MyAnnotation("Hello, this is a single-member annotation!")
is applied to themyMethod()
method. - The value
"Hello, this is a single-member annotation!"
is assigned to the single membervalue()
.
- Accessing the Annotation:
- In the
main()
method, the program uses reflection to access theMyAnnotation
annotation applied to themyMethod()
method. - The
value()
of the annotation is then printed out.
Output:
When you run the program, the output will be:
myMethod is executed. Annotation value: Hello, this is a single-member annotation!
Key Points:
- Single-Member Annotation: A special type of annotation with only one element, where you only need to provide the value directly without specifying the name.
- value() Method: The name of the element in a single-member annotation must be
value()
. - Usage: Simplifies the syntax when using annotations with only one value to set.