Annotations in Java

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());
    }
}

Sie befinden sich auf einer archivierten Version von karllorey.de. Diese Seite wird seit 2015 nicht mehr aktualisiert. Blog-Artikel haben jeweils den Stand des Veröffentlichungsdatums.

Weitere Informationen finden Sie im letzten Blog-Artikel. Meine Webseite finden Sie nun unter karllorey.com.