Definition der Annotation
package aufgabe13;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface Student {
String name();
int matrikel();
}
Nutzung der Annotation
package aufgabe13;
/**
*
* @author Karl Lorey
*
*/
@Student(name = "Peter Müller", matrikel = 3141592)
public class Application {
public static void main(String[] args) {
if (hasStudentAnnotation(Application.class)) {
printStudentAnnotation(Application.class);
}
}
private static boolean hasStudentAnnotation(Class<?> c) {
return c.isAnnotationPresent(Student.class);
}
private static void printStudentAnnotation(Class<?> c) {
Student s = c.getAnnotation(Student.class);
System.out.println("Student Information:");
System.out.println("- Name: " + s.name());
System.out.println("- Matrikel: " + s.matrikel());
}
}