Java反射機制

1 定義
在運行過程中,可以動態(tài)的調(diào)用任意一個類的屬性和方法。

2 反射的好處
一般分為靜態(tài)編譯、動態(tài)編譯兩種。
靜態(tài)編譯:在編譯時確定類型,綁定對象,即通過。
動態(tài)編譯:運行時確定類型,綁定對象。動態(tài)編譯最大限度發(fā)揮了java的靈活性,體現(xiàn)了多態(tài)的應(yīng)用,用以降低類之間的藕合性。反射即這里的動態(tài)編譯方式。

3 反射的主要操作
主要操作包括四個部分:獲取類操作;獲取屬性字段操作;獲取方法操作;獲取構(gòu)造方法操作。每一類的操作,如下:

/**
 * 反射知識點學(xué)習(xí)
 */
public class ReflectDemo {

    public static void main(String[] args) throws InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException, NoSuchFieldException
    {
        //獲取類名稱
        getReflectClassName();

        //獲取類方法
        getReflectClassMethodName();

        //獲取類域名
        getReflectClassFieldName();

        //獲取構(gòu)造方法
        getReflectClassConstructFunction();
    }

    @SuppressWarnings("unchecked")
    private static void getReflectClassName() throws InstantiationException, IllegalAccessException
    {
        Class<ReflectDemo> class1 = ReflectDemo.class;
        System.out.println("class1: " + class1);

        try {
            Class<ReflectDemo> class2 = (Class<ReflectDemo>) Class.forName("com.jesse.learn.reflect.ReflectDemo");
            System.out.println("class2: " + class2);
        }
        catch (ClassNotFoundException e) {
            System.out.println("ClassNotFoundException");
        }

        ReflectDemo reflectDemo = ReflectDemo.class.newInstance();
        Class<ReflectDemo> class3 = (Class<ReflectDemo>) reflectDemo.getClass();
        System.out.println("class3: " + class3);
    }

    private static void getReflectClassMethodName() throws NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, InvocationTargetException {
        Class<Student> class1 = Student.class;

        //reflecting all the declared methods of the class or interface represented by this Class object,
        //including public, protected, default (package) access, and private methods,
        //but excluding inherited methods
        for (Method method : class1.getDeclaredMethods()) {
            System.out.println("getDeclaredMethods: " + method.getName());
        }

        //reflecting all the public methods of the class or interface represented by this Class object,
        //including those declared by the class or interface
        //and those inherited from superclasses and superinterfaces
        for (Method method : class1.getMethods()) {
            System.out.println("getMethods: " + method.getName());
        }

        Student stu = class1.newInstance();
        Method method1 = class1.getMethod("setName", String.class);
        method1.invoke(stu, "wanghairong");
        System.out.println(stu.getName());

        Method method2 = class1.getMethod("getName");
        System.out.println(method2.invoke(stu));

        Method method3 = class1.getMethod("getAge");
        System.out.println(method3.invoke(stu));
    }

    private static void getReflectClassFieldName() throws NoSuchFieldException, SecurityException, InstantiationException, IllegalAccessException
    {
        Class<Student> class1 = Student.class;

        //all the accessible public fields of the class or interface represented by this Class object.
        for (Field field : class1.getFields()) {
            System.out.println("Fields: " + field.getName());
        }

        //reflecting all the fields declared by the class or interface represented by this Class object.
        //This includes public, protected, default (package) access, and private fields, but excludes inherited fields
        for (Field field : class1.getDeclaredFields()) {
            System.out.println("DeclaredFields: " + field.getName());
        }

        Field field1 = class1.getDeclaredField("name");
        Student stu = class1.newInstance();
        stu.setName("chengyingjie");

        field1.setAccessible(true);  //私有變量必須設(shè)置訪問權(quán)限,否則無法直接訪問
        System.out.println("name: " + field1.get(stu));
    }

    private static void getReflectClassConstructFunction() throws NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {

        Class<Student> class1 = Student.class;
        for (Constructor<?> constructor : class1.getConstructors()) {
            System.out.println("Constructors: " + constructor.getName());
        }

        for (Constructor<?> constructor : class1.getDeclaredConstructors()) {
            System.out.println("DeclaredConstructors: " + constructor.getName());
        }

        //注意:如果聲明了帶整型參數(shù)的構(gòu)造函數(shù),其參數(shù)必須聲明為Integer,否則,因int不是一個包裝類型,反射構(gòu)建時會報錯
        Constructor<Student> constructor = class1.getConstructor(String.class, Integer.class);
        System.out.println("Constructor: " + constructor.getName());

        Student stu2 = constructor.newInstance("chengwang", 20);
        System.out.println("constructorInstance: " + stu2.getName() + ":" + stu2.getAge());
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容