Demo:
public static void main(String[] args) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
Test test = new Test(4,5);
Field field1 = test.getClass().getDeclaredField("x");
field1.setAccessible(true);
System.out.println(field1.get(test)); }
class Test {
private int x;
public int y;
public Test(int x, int y) {
super();
this.x = x;
this.y = y;
}
以上为暴力反射的一个例子。下面是需要抛出的异常(有提示)
- NoSuchFieldException
- IllegalAccessException
重写的clone()需要抛出 CloneNotSupportedException