日期:2014-05-20  浏览次数:20704 次

怎样通过反射获得一个类的属性值或者方法返回值
  新建了一个TestReflect类ref。ref.length=1,ref.wight=2.
  但是为什么利用反射获得length还是默认值0啊?
  附代码,请各位大神指导

package reflect;

import java.lang.reflect.Method;

public class ReflectTest {
public static void main(String[] args) {
TestReflect ref=new TestReflect();
ref.setLength(1);
ref.setWight(2);

try {
Class<?> obj=Class.forName(ref.getClass().getName());
Object object = obj.newInstance();
Method method=obj.getMethod("getLength");
System.out.println(method.invoke(object));
} catch (Exception e) {
e.printStackTrace();

}
}


class TestReflect{

int length;
int wight;

TestReflect(){

}

public int getLength() {
return length;
}

public void setLength(int length) {
this.length = length;
}

public int getWight() {
return wight;
}

public void setWight(int wight) {
this.wight = wight;
}



}

------解决方案--------------------
Class<?> obj=Class.forName(ref.getClass().getName());
            Object object = obj.newInstance();
            Method method=obj.getMethod("getLength");

你这样拿到的是你newInstance新构建的对象,又不是你之前设定了值的对象,域当然会是0.

应该是这样:method.invoke(ref)