将字符串转换为整数成员,可能吗?

时间:2012-05-06 07:01:25

标签: java string casting

好吧我的问题并不是一个严肃的问题,我只是想找到一种访问/修改类成员变量的聪明方法。这是代码:

public class Storage{
 private int cookies= 0; 
 private int rolls= 0; 
 private int candies= 0; 
 private int lolipops= 0; 
 private int iceCreams= 0; 

 public void addCookies(int howMuch){  //this is the dirty way of creating method for
    this.cookies = cookies+howMuch;     //every member variable    
 }

 public void addValue(String stat, int howMuch){ //i would like to do it only
                                       //by passing the name
                                      //of variable and then cast it as integer
                                      //so that it would relate to my class members

    int value = this.(Integer.parseInt(stat));   //  <- YES i know its ridiculous
                                      //im just trying to explain what is my aim       
    value = value + howMuch;

    this.(Integer.parseInt(stat)) = value;
 }
}

通常我想通过将其名称传递给方法,读取该成员的值,添加一些值,然后存储它来访问字段。是的,我知道可以使用单独的方法轻松完成,甚至可以使用一些arraylist和成员名称与传递给方法的参数进行比较。但我想在没有多余代码编写的情况下“快速”完成。

现在我有5个成员,但是15000呢?我的目标是简化整个处理和代码编写。那么通常可以做这样的冗余代码写旁路吗?既然我知道我总会将适当的名称传递给方法......除非经验法则是为每个变量创建方法吗?

3 个答案:

答案 0 :(得分:3)

通常你会使用像Map这样的集合。

public class Storage{
    private final Map<String, Integer> inventory = ...

    public void addCount(String key, int count) {
        Integer i = inventory.get(key);
        if (i == null) i = 0;
        inventory.put(key, i + count);
    }

答案 1 :(得分:2)

我想通过使用反射,您可以遍历对象的字段/方法并进行计算。

对于某个特定领域:

    Field member = myObject.getClass().getField(fieldName);
    // If you know the class: Field member = MyClass.class.getField(fieldName);
    System.out.println(member.getInt(myObject)); // Get the value
            member.setInt(myObject, 4); // Set the value

如果您想为所有公共成员提供某些内容:

    for(Field member: myObject.getClass().getFields())
        // Or you can do: for(Field member: myClass.class.getFields())
    {
        member.getInt(myObject)); // Get the value
        member.setInt(myObject, 4); // Set the value
    }

基本上,你所做的是找到代表你对象成员的Field对象,然后你可以操纵它。

答案 2 :(得分:1)

大多数IDE都会为您生成setter和getter。这将做你想要的,没有麻烦或努力。如果这不够,请编写一个使用反射来设置值的方法。

如果你有一个拥有15000名成员的班级,并且我认为你的意思是对一个班级私有的变量,那么你还有其他问题需要解决。

相关问题