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

标签 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;
 }
}

通常我想通过将名称传递给方法来访问字段,读取该成员的值,向其添加一些值,然后存储它。是的,我知道它可以很容易地用单独的方法来完成,甚至可以通过使用一些数组列表和成员名称与传递给方法的参数的比较来完成。但我想在不编写冗余代码的情况下“快速”完成。

现在我有大约 5 个成员,但是 15000 个呢?我的目标是简化整个处理和代码编写。那么一般这样的冗余代码写绕过有没有可能呢?因为我知道我将始终将适当的名称传递给方法...除非经验法则是为每个变量创建方法?

最佳答案

通常您会使用像 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);
    }

关于java - 将字符串转换为整数成员,可能吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10468807/

相关文章:

java - 如何将 JFace Treeviewer 中的数据选择解析到 RCP 中的另一个 View ?

java - 如何在测试基于 CamelSpringTestSupport 的测试期间设置属性值

java - 用不可见字符(制表符、回车符、组分隔符等)分隔字符串?

c++ - 使用 boost::regex 匹配两个完整的单词

java - 在参数化 JUnit 4+ 测试中测试可选异常

java - Mac OS 中的 Pip 安装错误(错误 : command '/usr/bin/clang' failed with exit status 1)

c# - 当我在客户端分配变量时,无效的表达式术语 'string'

java - Java 中的向下转型

sql - 将十进制数转换为 INT SQL

c++ - 在 C++ 中将数字转换为字符串的最佳方法?