class A {
private int i;
public int getI(){
return i;
}
private void setI(int i) {
this.i = i;
}
}
Class<?> clazz= Class.forName("hadoopclient.A");
Field iField =clazz.getDeclaredField("i");
System.out.println("i: "+iField);
Method getI = clazz.getMethod("getI", newClass[]{});
System.out.println("getI: "+getI);
Method setI = clazz.getDeclaredMethod("setI", newClass[]{int.class});
System.out.println("setI: "+setI);
Object newInstance = clazz.newInstance();
Object returnValue = getI.invoke(newInstance,newClass<?>[]{});
System.out.println("init: "+returnValue);
setI.setAccessible(true); //若无此句将抛异常
setI.invoke(newInstance, newObject[]{100});
returnValue = getI.invoke(newInstance, newClass<?>[]{});
System.out.println("invokesetI(100): "+returnValue);
}
}
注意:
setAccessible(true)并不是将方法的访问权限改成了public,而是取消java的权限控制检查。所以即使是public方法,其accessible属相默认也是false
JDK 文档:
setAccessible
public void setAccessible(boolean flag) throws SecurityException
- Setthe accessible flag forthis object to the indicated boolean value. A valueof true indicates thatthe reflected object should suppress Java language access checkingwhen it is used. A valueof false indicates thatthe reflected object should enforce Java language access checks.
First, if there is a security manager,its
checkPermission
methodis called withaReflectPermission("suppressAccessChecks")
permission.A
SecurityException
israisedifflag
istrue
butaccessibility of this object may not be changed (for example, ifthis element object is aConstructor
objectfor the classClass
).A
SecurityException
israised if this object is aConstructor
objectfor the classjava.lang.Class
,andflag
istrue. - Parameters:
flag
- the new value forthe accessible flag- Throws:
SecurityException
-if the request is denied.- See Also:
SecurityManager.checkPermission(java.security.Permission)
,RuntimePermission