0

I want to be able to write a method with a string and integer as the parameters for example, and I want to then create a variable inside that class with the integer value in which I can later recall. For example:

public void setInt(String identifier, Integer) {

}

if I then call

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

it would create a variable called age, which I could later access by calling

getInt("age") //would return 25

How would I go about doing this?

1
  • 2
    Take a look at Maps. it will not create a variable, but will give you the desired functionality. Commented Mar 3, 2014 at 20:41

2 Answers 2

3

You could hold a Map data member, and use it to store values:

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);
}
Sign up to request clarification or add additional context in comments.

Comments

0

If you had a Map you could do that or if you used reflection. The best way is to just create a getter and setter pair per instance variable:

private int age;

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

public int getAge() {
    return age;
}

If you had a map like the following, you could achieve this:

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");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.