一、注意事项
* <br>
* 主要方法:
* 得到Annotation信息(Class): public Annotation[] getAnnotations() {}
*
* 不同的Annotation会有不同的读取时间
* <br>
* 观察:这个Annotation是运行时生效
* @Documented
* @Retention(RetentionPolicy.RUNTIME)
* @Target(ElementType.TYPE)
* public @interface FunctionalInterface {}
*
* 观察:这是在源代码才能获取
* @Target(ElementType.METHOD)
* @Retention(RetentionPolicy.SOURCE)
* public @interface Override {}
* <br>
* 观察:不同时间爱你生效就表示在这里,分别时源代码,字节码,运行时
* public enum RetentionPolicy { SOURCE, CLASS, RUNTIME}
* <br>
二、完整代码
package reflect.annotation;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
public class GetAnnotationInfo {
public static void main(String[] args) throws NoSuchMethodException {
System.out.println("--------------------");
Annotation[] anIMsgs = IMessage.class.getAnnotations();
for (Annotation a : anIMsgs) {
System.out.println(a);
}
System.out.println("---------------------");
Annotation[] anMsgs = MyMessage.class.getAnnotations();
for (Annotation a : anMsgs) {
System.out.println(a);
}
System.out.println("---------------------");
Method method = MyMessage.class.getMethod("spend" , String.class);
Annotation[] anMethods = method.getAnnotations();
for (Annotation a : anMethods) {
System.out.println(a);
}
}
}
@FunctionalInterface
@Deprecated
interface IMessage {
public void spend(String msg);
}
@SuppressWarnings("unchecked")
class MyMessage implements IMessage{
@Override
public void spend(String msg) {
System.out.println(msg);
}
}
三、运行结果
--------------------
@java.lang.FunctionalInterface()
@java.lang.Deprecated(forRemoval=false, since="")
---------------------
---------------------