Java反射獲取私有構造方法的屬性,方法

package com.jsdc.tianqi.test;

import com.jsdc.tianqi.danli.CarFactory;

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

public class Test1 {

    public static void main(String[] args) throws Exception {
        try {
            Class<?> clazz = CarFactory.class;// 獲取自定義CarFacotry整個類
            Constructor<?> declaredConstructor = clazz.getDeclaredConstructor();
            declaredConstructor.setAccessible(true);
            CarFactory pc = (CarFactory) declaredConstructor.newInstance();// 創建一個實例

            Field[] fs = clazz.getDeclaredFields();// 獲取PrivateClass所有屬性
            for (int i = 0; i < fs.length; i++) {
                fs[i].setAccessible(true);// 將目標屬性設置爲可以訪問
                System.out.println("賦值前:" + fs[i].getName() + ":" + fs[i].get(pc));
                String s = fs[i].getGenericType().toString();//獲取type類型
                if (s.equals("class java.lang.String")){
                    fs[i].set(pc, "我是factoryName");//將屬性值重新賦值
                }else{

                    fs[i].set(pc, null);//將屬性值重新賦值
                }

                System.out.println("賦值後:" + fs[i].getName() + ":" + fs[i].get(pc));
            }

            Method[] ms = clazz.getDeclaredMethods();// 獲取PrivateClass所有的方法
            for (int i = 0; i < ms.length; i++) {
                ms[i].setAccessible(true);// 將目標屬性設置爲可以訪問
                System.out.println("方法 : " + ms[i].getName());//輸出所以方法的名稱
            }
            Method m = clazz.getDeclaredMethod("setFactoryName",new Class[]{String.class});
            m.setAccessible(true);
            System.out.println("url方法返回值:" +
                    m.invoke(pc, new Object[] {"我是工廠名稱"}));//得到結果應該是重新賦值後的值null:null
            Field factoyName = clazz.getDeclaredField("factoyName");
            factoyName.setAccessible(true);
            Object o = factoyName.get(pc);
            System.out.println("屬性factoryName的值:"+o);
            System.out.println(factoyName);
        } catch (InstantiationException | IllegalAccessException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

    }
}

由此可見,幾時是private修飾了,也可以被獲取 和賦值

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章