一个类中要有这个名字的变量,你才能使用它。所以假设有一个类
public class SomeObject{
private String msg0,msg1,msg2,msg3,msg4,msg5;//既然这样,干吗不定义一个数组呢?
...
public void setMsg5(String msg){
this.msg5=msg;
}
public String getMsg5(){
return msg5;
}
...
}
OK,不管这样声明变量是否合理,有一个办法可以使用变量的值。
假设为所有这样的变量设置了get和set方法(如上代码),则可以像下面这样使用
String methodNameGet="getMsg";
String methodNameSet="setMsg";
SomeObject o=new SomeObject();
    Method mg=null;
    try {
        mg = o.getClass().getMethod(ng,null);
        msg=mg.invoke(o,null);
        System.out.println("msg"+i+"="+msg);
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    }
}
这个过程真有点费事,用数组也许比较明智

解决方案 »

  1.   

    sorry,漏贴了代码
       String methodNameGet="getMsg";
    String methodNameSet="setMsg";
    SomeObj o=new SomeObj();
    Object msg;
    for(int i=0;i<=5;i++){
    String ng=methodNameGet+i;
        Method mg=null;
        try {
            mg = o.getClass().getMethod(ng,null);
            msg=mg.invoke(o,null);
            System.out.println("msg"+i+"="+msg);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
      

  2.   

    我想问这个问题的原因是这样的,我以前常用flash做游戏,拿俄罗斯方块来说,在写代码时有时候需要得到一个方块的索引值,比如是5,然后我就可以通过一个变量名比如rec5来控制名为rec5的这个Object。现在我转到j2me上,却碰到类似的情况不知道是否java中也有这样的办法来合成一个变量名,chanceqw的办法我没有尝试,也许可行但是过程太过繁琐,有没有其他简单的解决方案?或者说,各位有碰到类似问题的时候是怎么解决的?
      

  3.   

    如果变量不是很多的话,也可以用switch(){case}
    不过没有这样使用过变量,我一般都是用数组或者集合来解决的