:
13.5.7.
, . . , , Java. , API, . API- .
Java.
:
13.5.3.
.
, , .
, .
@Retention(RetentionPolicy.RUNTIME)
@Target (ElementType.TYPE)
@interface MyAnnotation {
String foo ();
}
:
@FooAnnotation(foo = "Foo")
public class MyAnnotatedClass {
public static void main (String[] args) {
FooAnnotation annot = MyAnnotatedClass.class.getAnnotation(FooAnnotation.class);
Method[] methods = FooAnnotation.class.getDeclaredMethods();
System.out.println("Methods:");
for (Method method : methods) {
System.out.println(method.getName() + "() returns:\n");
try {
String value = (String) method.invoke(annot);
System.out.println("\t" + value);
} catch (Exception e) {
System.out.println("\tERROR! " + e.getMessage());
}
}
}
}
, :
Methods:
foo() returns:
Foo
:
@Retention(RetentionPolicy.RUNTIME)
@Target (ElementType.TYPE)
@interface MyAnnotation {
String foo ();
String bar ();
}
, MyAnnotatedClass. - : MyAnnotation , , MyAnnotatedClass . , :
Methods:
bar() returns:
ERROR! null
foo() returns:
Foo
? ! , bar() . , , , .
, . , :
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at example.MyAnnotatedClass.main(MyAnnotatedClass.java:16)
Caused by: java.lang.annotation.IncompleteAnnotationException: example.FooAnnotation missing element bar
at sun.reflect.annotation.AnnotationInvocationHandler.invoke(Unknown Source)
at com.sun.proxy.$Proxy1.bar(Unknown Source)
... 5 more
bar() IncompleteAnnotationException. Javadoc :
, , , ( ). , . API, .