1. 程式人生 > 實用技巧 >註解與反射 完結撒花!!!

註解與反射 完結撒花!!!

動態建立物件執行方法(20-12-14)

建立類的物件:呼叫Class物件的 newInstance()方法

  1. 類必須有一個無參構造
  2. 類的構造器的訪問許可權需要足夠

使用invoke方法啟用obj物件 Object invoke(Object obj,Object ... args)

若原方法若為靜態方法,此時形參Object obj可為null

若原方法形參列表為空,則Object[] args為null

若原方法宣告為private,則需要在呼叫此invoke()方法前,顯式呼叫方法物件的setAccessible(true)方法(改變許可權),將可訪問private的方法。

效能對比分析
//效能對比分析
public class Test05 {

    //普通方式呼叫
    public static void test01(){
        User user = new User();
        long startTime=System.currentTimeMillis();

        for (int i = 0; i < 1000000000; i++) {
            user.getName();
        }

        long endTime=System.currentTimeMillis();
        System.out.println("普通方式執行10億次:"+(endTime-startTime)+"ms");
    }

    //反射方式呼叫
    public static void test02() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        User user = new User();
        Class c1=user.getClass();
        Method getName=c1.getDeclaredMethod("getName",null);

        long startTime=System.currentTimeMillis();

        for (int i = 0; i < 1000000000; i++) {
            getName.invoke(user,null);
        }

        long endTime=System.currentTimeMillis();
        System.out.println("反射方式執行10億次:"+(endTime-startTime)+"ms");
    }

    //反射方式呼叫 關閉檢測
    public static void test03() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        User user = new User();
        Class c1=user.getClass();
        Method getName=c1.getDeclaredMethod("getName",null);
        getName.setAccessible(true);

        long startTime=System.currentTimeMillis();

        for (int i = 0; i < 1000000000; i++) {
            getName.invoke(user,null);
        }

        long endTime=System.currentTimeMillis();
        System.out.println("關閉檢測執行10億次:"+(endTime-startTime)+"ms");
    }

    public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
        test01();
        test02();
        test03();
    }
反射操作泛型
//通過反射獲取泛型
public class Test06 {
    public void test01(Map<String,User> map, List<User> list){
        System.out.println("test01");
    }

    public Map<String,User> test02(){
        System.out.println("test02");
        return null;
    }

    public static void main(String[] args) throws NoSuchMethodException {
        Method method=Test06.class.getMethod("test01", Map.class, List.class);
        Type[] genericParameterTypes = method.getGenericParameterTypes();

        for (Type genericParameterType : genericParameterTypes) {
            System.out.println("#"+genericParameterType);
            if(genericParameterType instanceof ParameterizedType){
                Type[] actualTypeArguments = ((ParameterizedType) genericParameterType).getActualTypeArguments();
                for (Type actualTypeArgument : actualTypeArguments) {
                    System.out.println(actualTypeArgument);
                }
            }
        }

         method=Test06.class.getMethod("test02",null);
        Type genericReturnType = method.getGenericReturnType();
        if(genericReturnType instanceof ParameterizedType){
            Type[] actualTypeArguments = ((ParameterizedType) genericReturnType).getActualTypeArguments();
            for (Type actualTypeArgument : actualTypeArguments) {
                System.out.println(actualTypeArgument);
            }
        }
    }

}
反射操作註解
//反射操作註解
public class Test07 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException {
        Class c1 = Class.forName("reflection.Student2");

        //通過反射獲得註解
        Annotation[] annotations = c1.getAnnotations();
        for (Annotation annotation : annotations) {
            System.out.println(annotation);
        }
        System.out.println("============================");

        //獲得註解的value的值
        Tablekuang tablekuang = (Tablekuang) c1.getAnnotation(Tablekuang.class);
        String value=tablekuang.value();
        System.out.println(value);
        System.out.println("============================");

        //獲得類指定的註解
        Field f = c1.getDeclaredField("name");
        Fieldkuang annotation = f.getAnnotation(Fieldkuang.class);
        System.out.println(annotation.columnName());
        System.out.println(annotation.type());
        System.out.println(annotation.length());
    }

}

@Tablekuang("db_student")
class Student2{
    @Fieldkuang(columnName = "db_id",type = "int",length = 10)
    private int id;
    @Fieldkuang(columnName = "db_age",type = "int",length = 10)
    private int age;
    @Fieldkuang(columnName = "db_name",type = "varchar",length = 3)
    private String name;

    public Student2(int id, int age, String name) {
        this.id = id;
        this.age = age;
        this.name = name;
    }

    public Student2() {
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Student2{" +
                "id=" + id +
                ", age=" + age +
                ", name='" + name + '\'' +
                '}';
    }
}

//類名的註解
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface Tablekuang{
    String value();
}

//屬性的註解
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface Fieldkuang{
    String columnName();
    String type();
    int length();
}

註解與反射 完結撒花!!!