关于Java中变量的问题!在线等解,急!!!

来源:百度知道 编辑:UC知道 时间:2024/07/05 07:24:56
现在,一个类中有变量int var,方法p(String s,int n)。
如果给p传入参数("var",10),怎样能使给变量var赋值10.
我说的有点问题,不好意思。
预先是不知道要给var赋值的,比如这个类中有好多个变量。是动态的根据输入的变量名,来给对应的变量赋值 。

利用反射,返回false说明赋值不成功,返回true说明赋值成功。
另:你的的需求很奇怪,你确定真的没有别的办法解决了吗?反射的速度毕竟没那么快。

boolean p(String s,int n){
try {
Class clazz=this.getClass();
java.lang.reflect.Field f=clazz.getDeclaredField(s);
f.setInt(this,n);
return true;
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return false;
}

public class T{
int var;
public void p(String s,int n){
this.var = n;
}
}

这样就可以了,那个参数(String s,)没太大的用途~~

类中变量?是类中成员吧,你说的这种情况要用反射
p(String s,int i) {
Test t = new Test();
Class<?> cls = t.getClass();
Field f = cls.getDeclaredField(s);
f.setAccessible(true);