java訪問類的私有變數和方法
阿新 • • 發佈:2019-02-17
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
class A {
private String a = "私有變數1";
private String b = "私有變數2";
private String hidden()
{
return "我是私有方法,不可見";
}
}
public class B {
public static void main(String []args) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
A node = new A();
Method [] methods = A.class.getDeclaredMethods();
for(Method m:methods)
{
//修改方法的訪問許可權
m.setAccessible(true);
System.out.println(m.invoke(node));
}
Field []fields = A.class.getDeclaredFields();
for(Field field : fields) {
field.setAccessible(true);
try {
System.out.println(field.get(node));
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
}
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
class A {
private String a = "私有變數1";
private String b = "私有變數2";
private String hidden()
{
return "我是私有方法,不可見";
}
}
public class B {
public static void main(String []args) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
A node = new A();
Method [] methods = A.class.getDeclaredMethods();
for(Method m:methods)
{
//修改方法的訪問許可權
m.setAccessible(true);
System.out.println(m.invoke(node));
}
Field []fields = A.class.getDeclaredFields();
for(Field field : fields) {
field.setAccessible(true);
try {
System.out.println(field.get(node));
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
}