Class< > c = Class.forName("com.itmyhome.Demo");
Method mt = c.getMethod("toString"); //找到toString方法
Annotation an[] = mt.getAnnotations(); //取得全部的Annotation
for(Annotation a:an){
System.out.println(a);
}
}
}
package com.itmyhome;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
class Demo{
@SuppressWarnings("unchecked")
@Deprecated
@Override
public String toString(){
return "hello";
}
}
public class T {
public static void main(String[] args) throws Exception{
Class< > c = Class.forName("com.itmyhome.Demo");
Method mt = c.getMethod("toString"); //找到toString方法
Annotation an[] = mt.getAnnotations(); //取得全部的Annotation
for(Annotation a:an){
System.out.println(a);
}
}
}
此时已经取得了一个Annota。以上的操作实际上是通过三个系统内建的Annotation完成的,也可以自定义一个Annotation
[java] @Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Meaning {
FormItemType value() ; //设置为枚举类型
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Meaning {
FormItemType value() ; //设置为枚举类型
}
[java] package com.itmyhome;
import java.lang.reflect.Method;
class Demo{
@Meaning(value=FormItemType.select) //自定义Annotation
@SuppressWarnings("unchecked")
@Deprecated
@Override
public String toString(){
return "hello";
}
}
public class T {
public static void main(String[] args) throws Exception{
Class< > c = Class.forName("com.itmyhome.Demo");
Method mt = c.getMethod("toString"); //找到toString方法
//指定的注释是否存在于此元素上
if(mt.isAnnotationPresent(Meaning.class)){
Meaning m = mt.getAnnotation(Meaning.class); //得到指定的Annotation
System.out.println(m.value()); //取得Annotation的值
}
}
}
package com.itmyhome;
import java.lang.reflect.Method;
class Demo{
@Meaning(value=FormItemType.select) //自定义Annotation
@SuppressWarnings("unchecked")
@Deprecated
@Override
public String toString(){
return "hello";
}
}
public class T {
public static void main(String[] args) throws Exception{
Class< > c = Class.forName("com.itmyhome.Demo");
Method mt = c.getMethod("toString"); //找到toString方法
//指定的注释是否存在于此元素上
if(mt.isAnnotationPresent(Meaning.class)){
Meaning m = mt.getAnnotation(Meaning.class); //得到指定的Annotation
System.out.println(m.value()); //取得Annotation的值
}
}
}
@Target
指示注释类型所适用的程序元素的种类。如果注释类型声明中不存在 Target 元注释,则声明的类型可以用在任一程序元素上。如果存在这样的元注释,则编译器强制实施指定的使用限制,如:@Target(ElementType.ANNOTATION_TYPE)
ElementType的保存范围