In Java, how to get attribute given the string with its name?

If I understand your question correctly... You should create public getters and setters:

public void setMyColor(String color) {
    this.myColor = color;
}

public String getMyColor {
    return this.myColor;
}

Based on the edit, my suggestion is to use a Map to contain a map of preference name to appropriate text field or other text component. Just build the map when you build the user interface.

Map<String, JTextField> guiFields = new HashMap<String, JTextField>();

Then you can have the code do

guiFields.get(inputName).setText(value);

You can use reflection to inspect the content of any object, as follows:

Object o = ...; // The object you want to inspect
Class<?> c = o.getClass();

Field f = c.getDeclaredField("myColor");
f.setAccessible(true);

String valueOfMyColor = (String) f.get(o);

Note that getDeclaredField() will only return field's declared by the object's class. If you're looking for a field that was declared by a superclass you should loop over all classes of the object (by repeatedly doing c = c.getSuperclass() until c == null)

If you want to change the value of the field you can use the set method:

f.set(o, "some-new-value-for-field-f-in-o")

Additional details: https://docs.oracle.com/javase/6/docs/api/java/lang/reflect/Field.html


https://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#getField(java.lang.String)

You can use getField(...) which will search on super class if not found in class.

Tags:

Java