Java annotation: Difference between revisions

Content deleted Content added
No edit summary
No edit summary
Line 60:
<syntaxhighlight lang="java">
public class Animal {
public void speak() {}
}
 
public String getType() {
Line 86 ⟶ 85:
 
<syntaxhighlight lang=Java>
// @Twizzle is an annotation to method toggle().
@Twizzle
public void toggle() {
}
 
}
// Declares the annotation Twizzle.
 
public @interface Twizzle {
// Declares the annotation Twizzle.
}
public @interface Twizzle {
 
}
</syntaxhighlight>
 
Line 99 ⟶ 100:
 
<syntaxhighlight lang=Java>
// Same as: @Edible(value = true)
@Edible(true)
Item item = new Carrot();
 
public @interface Edible {
boolean value() default false;
}
 
@Author(first = "Oompah", last = "Loompah")
Book book = new Book();
 
public @interface Author {
String first();
String last();
}
</syntaxhighlight>
 
Line 119 ⟶ 120:
 
<syntaxhighlight lang=Java>
@Retention(RetentionPolicy.RUNTIME) // Make this annotation accessible at runtime via reflection.
@Target({ElementType.METHOD}) // This annotation can only be applied to class methods.
public @interface Tweezable {}
}
</syntaxhighlight>
 
Line 261:
String developer() default "Unknown";
String lastModified();
String [] teamMembers();
int meaningOfLife();
}
Line 284:
 
public class UseCustomAnnotation {
public static void main(String [] args) {
Class<SetCustomAnnotation> classObject = SetCustomAnnotation.class;
readAnnotation(classObject);
Line 291:
static void readAnnotation(AnnotatedElement element) {
try {
System.out.println("Annotation element values: \%n");
if (element.isAnnotationPresent(TypeHeader.class)) {
// getAnnotation returns Annotation type
Annotation singleAnnotation = element.getAnnotation(TypeHeader.class);
element.getAnnotation(TypeHeader.class);
TypeHeader header = (TypeHeader) singleAnnotation;
 
System.out.printlnprintf("Developer: %s%n" +, header.developer());
System.out.printlnprintf("Last Modified: %s%n" +, header.lastModified());
 
// teamMembers returned as String []
System.out.print("Team members: ");
for (String member : header.teamMembers()) {
System.out.printprintf(member + "%s, ", member);
System.out.print("\n");}
System.out.println();
 
System.out.println("Meaning of Life: %s%n"+, header.meaningOfLife());
}
} catch (Exception exception) {