java基礎之註解

java基礎之註解

自定義註解:

@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
    String name();
    int age();
}

測試代碼:

public class AnnotationTest {
    @MyAnnotation(name = "suvue",age=22)
    public void addUser(String name,Integer age){
        //執行業務邏輯
        //...
        System.out.println("用戶添加成功!姓名:"+name+" 年齡:"+ age);
    }

    public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InstantiationException, InvocationTargetException {
        //java是通過反射機制使註解生效
        //獲取類對象
        Class<AnnotationTest> aClass = AnnotationTest.class;
        //獲取到指定方法
        Method aClassMethod = aClass.getMethod("addUser", String.class, Integer.class);
        //獲取方法上的指定註解
        MyAnnotation aClassMethodAnnotation = aClassMethod.getAnnotation(MyAnnotation.class);
        //獲取註解裏的屬性和值
        int age = aClassMethodAnnotation.age();
        String name = aClassMethodAnnotation.name();
        //將信息注入到方法上
        AnnotationTest instance = aClass.newInstance();
        aClassMethod.invoke(instance,name,age);
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章