通过接口new的实现类的对象,通过什么方法能获取到这个类的属性值
public interface Test{
void method1();
void method2();
}
public class TestImpl implements Test{
private int v;
//getter and setter
public int getV() {
return v;
}
public void setV(int v) {
this.v = v;
}
public void method1(){
System.out.print("hello world!");
setV(100);
}
public void method2(){
System.out.print("hello java!");
setV(200);
}
}
Test test = new TestImpl();
test.method1();
//上面执行完之后,如何在这里获取属性v的值
//1、必须使用接口new对象
//2、v 不能定义为static类型
//3、不能使用线程绑定
可以用反射
Class testClass = test.getClass();
Field v = testClass.getDeclaredField("v");
v.setAccessible(true);
int value = (int)v.get(test);