註解和反射

fightownself發表於2024-08-09

註解和反射

image-20240806090340858

元註解

package lesson05;

import java.lang.annotation.*;

//定義元註解

public class Test01 {
    @MyAnnotation
    public void test(){}
}

//定義一個註解
//Target表示註解可以用在哪些地方
@Target(value = {ElementType.METHOD,ElementType.TYPE})
//Retention表示我們的註解在什麼地方還有效
//runtime>class>source
//Documented表示是否將註解生成在javadoc中
@Documented
//Inherited 子類可以繼承父類的註解
@Inherited
@Retention(value = RetentionPolicy.RUNTIME)
@interface MyAnnotation{

}

自定義註解

package lesson05;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

//自定義註解
public class Test02 {
    //註解可以顯示賦值,如果沒有預設值,就必須賦值
    @MyAnnotation2(schools = "大學")
    public void test(){}

    @MyAnnotation3("jf")
    public void test2(){}
}

@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation2{
    //註解的引數 引數型別 +引數名();
    String name() default "";
    int age() default 0;
    int id() default -1;//如果預設值為-1,代表不存在,indexof,如果找不到就返回-1.
    String[] schools();
}

@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation3{
    String value();
}

測試Class類的建立方式有哪些

package lesson05;

//測試Class類的建立方式有哪些
public class Test04 {
    public static void main(String[] args) throws ClassNotFoundException {
        Person person = new Student();
        System.out.println("這個人是:"+person.name);
        //方式一:透過物件獲得
        Class c1 = person.getClass();
        System.out.println(c1.hashCode());
        //方式二:forname獲得
        Class c2 = Class.forName("lesson05.Student");
        System.out.println(c2.hashCode());
        //方式三:透過類名.class獲得
        Class c3 = Student.class;
        System.out.println(c3.hashCode());
        //方式四:基本內建型別的包裝類都有一個Type屬性
        Class c4 = Integer.TYPE;
        System.out.println(c4);
        //獲得父類型別
        Class c5 = c1.getSuperclass();
        System.out.println(c5);
    }
}

class Person{
   public String name;

    public Person() {
    }

    public Person(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                '}';
    }
}

class Student extends Person{
    public Student(){
        this.name="學生";
    }
}
class Teacher extends Person{
    public Teacher(){
        this.name="老師";
    }
}

所有型別的Class

package lesson05;

import java.lang.annotation.ElementType;
import java.lang.annotation.Target;

//所有型別的Class
public class Test05 {
    public static void main(String[] args) {
        Class c1 = Object.class;//類
        Class c2 = Comparable.class;//介面
        Class c3 = String[].class;//一維陣列
        Class c4 = int[][].class;//二維陣列
        Class c5 = Override.class;//註解
        Class c6 = ElementType.class;//列舉
        Class c7 = Target.class;//基本資料型別
        Class c8 = void.class;
        Class c9 = Class.class;

        System.out.println(c1);
        System.out.println(c2);
        System.out.println(c3);
        System.out.println(c4);
        System.out.println(c5);
        System.out.println(c6);
        System.out.println(c7);
        System.out.println(c8);
        System.out.println(c9);

        //只要元素型別與維度一樣,就是同一個Class
        int[] a = new int[10];
        int[] b = new int[100];
        System.out.println(a.getClass().hashCode());
        System.out.println(b.getClass().hashCode());

    }
}

類載入器

package lesson05;

public class Test06 {
    static {
        System.out.println("Main類被載入");
    }

    public static void main(String[] args) throws ClassNotFoundException {
        //主動引用
       // Son son =new Son();
        //反射也會產生主動引用
        //Class.forName("lesson05.Son");
        //不會產生類的引用的方法
        //System.out.println(Son.b);
        //Son[] array=new Son[5];
        System.out.println(Son.M);
    }

}

class Father {
    static int b=2;
    static {
        System.out.println("父類被載入");
    }
}

class Son extends Father{
    static {
        System.out.println("子類被載入");
    }
    static int m=100;
    static final int M=1;
}

獲取類的載入器

package lesson05;

public class Test07 {
    public static void main(String[] args) throws ClassNotFoundException {
        //獲取系統類的載入器
        ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader();
        System.out.println(systemClassLoader);
        //獲取系統類的載入器的父類載入器--》擴充套件類載入器
        ClassLoader parent = systemClassLoader.getParent();
        System.out.println(parent);
        //獲取擴充套件類載入器的父類載入器-->根載入器(c++)
        ClassLoader parent1 = parent.getParent();
        System.out.println(parent1);
        //測試當前類是哪個載入器載入的
        ClassLoader classLoader = Class.forName("lesson05.Test07").getClassLoader();
        System.out.println(classLoader);
        //測試JDK內建類是誰載入的
        classLoader = Class.forName("java.lang.Object").getClassLoader();
        System.out.println(classLoader);
        //如何獲得系統類載入器可以載入的路徑
        System.out.println(System.getProperty("java.class.path"));
    }
}

獲取類的執行時結構

package lesson05;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class Test08 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, NoSuchMethodException {
        Class c1 = Class.forName("lesson05.User");
        //獲得類的名字
        System.out.println(c1.getName());//獲得包名+類名
        System.out.println(c1.getSimpleName());//獲得類名
        //獲得類的屬性
        Field[] fields = c1.getFields();//只能找到public屬性
        fields=c1.getDeclaredFields();//找到全部屬性
        for (Field field : fields) {
            System.out.println(field);
        }
        //獲得指定屬性的值
        Field name = c1.getDeclaredField("name");
        System.out.println(name);
        //獲得類的方法
        Method[] methods = c1.getMethods();//獲得本類及其父類的全部public方法
        for (Method method : methods) {
            System.out.println("正常的:"+method);
        }
        methods=c1.getDeclaredMethods();//獲得本類的所有方法
        for (Method method : methods) {
            System.out.println("getDeclaredMethods:"+method);
        }
        //獲得指定方法
        Method getname = c1.getMethod("getName",null);
        Method setname = c1.getMethod("setName", String.class);
        System.out.println(getname);
        System.out.println(setname);
        //獲得指定的構造器
        System.out.println("===============================");
        Constructor[] constructors = c1.getConstructors();
        for (Constructor constructor : constructors) {
            System.out.println(constructor);
        }
        constructors = c1.getDeclaredConstructors();
        for (Constructor constructor : constructors) {
            System.out.println("#"+constructor);
        }
        //獲得指定的構造器
        Constructor declaredConstructor = c1.getDeclaredConstructor(String.class, int.class);
        System.out.println("指定的:"+declaredConstructor);
    }
}

透過反射獲得方法和操作屬性

package lesson05;


import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

//動態的建立物件,透過反射
public class Test09 {
    public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException {
        //獲得class物件
        Class c1 = Class.forName("lesson05.User");

        //構造一個物件
        //User user = (User)c1.newInstance();//本質是呼叫了無參構造器
        //System.out.println(user);
        //透過構造器建立物件
//        Constructor constructor = c1.getDeclaredConstructor(String.class, int.class);
//        User user2 = (User) constructor.newInstance("jf", 90);
//        System.out.println(user2);

        //透過反射呼叫普通方法
        User user3 = (User)c1.newInstance();
        //透過反射獲取一個方法
        Method setName = c1.getDeclaredMethod("setName",String.class);
        //invoke:啟用的意思
        //(物件,“方法的值”)
        setName.invoke(user3,"jf");
        System.out.println(user3.getName());
        //透過反射操作屬性
        User user4 = (User)c1.newInstance();
        Field name = c1.getDeclaredField("name");
        name.setAccessible(true);//關閉私有屬性安全檢測,不能直接操作私有屬性
        name.set(user4,"jf");
        System.out.println(user4.getName());

    }
}

效能對比分析

package lesson05;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

//分析效能問題
public class Test10 {
    //普通方式呼叫
    public static void test1(){
        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 test2() 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 test3() 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 InvocationTargetException, NoSuchMethodException, IllegalAccessException {
        test1();
        test2();
        test3();
    }
}

反射操作泛型

package lesson05;

import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;

public class Test11 {
    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 = Test11.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 = Test11.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);
            }
        }
    }
}

透過反射操作註解

package lesson05;

import java.lang.annotation.*;
import java.lang.reflect.Field;

//練習反射操作註解
public class Test12 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException {
        Class c1 = Class.forName("lesson05.Student2");
        //透過反射獲得註解
        Annotation[] annotations = c1.getAnnotations();
        for (Annotation annotation : annotations) {
            System.out.println(annotation);
        }
        //獲得註解value的值
        Table01 table01 = (Table01)c1.getAnnotation(Table01.class);
        String value = table01.value();
        System.out.println(value);
        //獲得類指定的註解
        Field f = c1.getDeclaredField("name");
        Field01 annotation = f.getAnnotation(Field01.class);
        System.out.println(annotation.columName());
        System.out.println(annotation.type());
        System.out.println(annotation.length());


    }

}

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

    public Student2() {
    }

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

    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 Table01{
    String value();
}

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

相關文章