1秒登錄
一般在其他類中是不能這個得到類中private屬性和訪問private方法的,但天無絕人之路,java強大的反射機制可以完成這個任務。
建一個測試類A:
package com.shao.test; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; public class B { public static void main(String[]args) throws ClassNotFoundException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException, NoSuchMethodException, InvocationTargetException{ Field field=Class.forName("com.shao.test.A").getDeclaredField("testStr"); field.setAccessible(true); A a=new A(); System.out.println(field.getType().toString()); //print:class java.lang.String System.out.println(field.getName()); //print:testStr System.out.println(field.getModifiers()); //print:2 Object s=field.get(a); System.out.println(s); //print:just for test String x="Hello"; field.set(a, x); System.out.println(field.get(a)); //print:Hello Method method=Class.forName("com.shao.test.A").getDeclaredMethod("get", new Class[]{int.class,String.class}); method.setAccessible(true); method.invoke(a, 3,"apples"); //print:3:apples and testStr:Hello } }
本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。