自定义Annotation

自定义Annotation

自定义Annotation
早就知道jdk5加了新特性Annotation,但是没研究过,前几天公司培训,有一部分是介绍jdk5新特性的,一个是注解一个泛型
今儿复习一下注解
    //用@Deprecated声明该方法不建议使用
    @Deprecated public void doSomething1(){
        Map map = new HashMap();
        map.put("some", "thing");
        System.out.println(map);
    }
   
    //用@SuppressWarnings声明不再进行类型检查
    @SuppressWarnings(value={"unchecked"})
    public void doSomething2(){
        Map map = new HashMap();
        map.put("some", "thing");
    }


写一个自定义注解先
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
//要在运行时使用这个注解,必须声明成RUNTIME
Annotation分为三种级别:RUNTIME、CLASS、SOURCE
@Retention(RetentionPolicy. RUNTIME)
public @interface SomeAnnotation{
    String value();
    String name();
}

下面来使用这个自定义注解:
import java.lang.reflect.Method;
public class AnnotationTest {
   
    @SomeAnnotation(value= "value1",name= "name1")
    public void doSomething3(){
       
    }
   
    public static void main(String[] args){
   
        Class<AnnotationTest> c = AnnotationTest. class;
        try {
            //利用反射得到方法doSomething3
            Method method = c. getMethod( "doSomething3");
            //查找doSomething3方法是否有SomeAnnotation的Annotation
            if(method. isAnnotationPresent(SomeAnnotation. class)){
                System. out. println( "找到SomeAnnotation");
                //得到SomeAnnotation
                SomeAnnotation annotation = method. getAnnotation(SomeAnnotation. class);
                System. out. println( "annotation.value="+annotation. value());
                System. out. println( "annotation.name="+annotation. name());
            } else{
                System. out. println( "没有找到omeAnnotation");
            }
        } catch (SecurityException e) {
            e. printStackTrace();
        } catch (NoSuchMethodException e) {
            e. printStackTrace();
        }
    }
}

输出结果:
找到SomeAnnotation
annotation.value=value1
annotation.name=name1

你可能感兴趣的:(自定义Annotation)