使用字符串和值java创建预定义类型的字段

时间:2014-03-03 20:39:09

标签: java

我希望能够编写一个以字符串和整数作为参数的方法,然后我想在该类中创建一个带有整数值的变量,我可以在后面回忆一下。例如:

public void setInt(String identifier, Integer) {

}

如果我再打电话

setInt("age", 25); //stores 25 with identifier "age"

它会创建一个名为age的变量,稍后我可以通过调用

来访问它
getInt("age") //would return 25

我将如何做到这一点?

2 个答案:

答案 0 :(得分:3)

您可以拥有Map数据成员,并使用它来存储值:

public class SomeClass {
    // could (should?) be initialized in the ctor
    private Map<String, Integer> map = new HashMap<>();

    public void setInt (String identifier, int value) {
        // This assumes identifier != null, for clarity
        map.put (identifier, value);
    }

    public int getInt (String identifier) {
        return map.get (identifier);
}

答案 1 :(得分:0)

如果您有地图,您可以这样做,或者如果您使用反射。最好的方法是为每个实例变量创建一个getter和setter对:

private int age;

public void setAge(int age) {
    this.age = age;
}

public int getAge() {
    return age;
}

如果您有如下地图,则可以实现此目的:

Map<String, Object> properties = new HashMap<>();

public void setInt(String property, int value) {
    properties.put(property, value);
}

public int getInt(String property) {
    return (int) properties.get(property);
}

// Usage
setInt("age", 25);
int age = getInt("age");