user2914191 user2914191 - 11 days ago 6
Java Question

Java get property name as string

Is it possible to get property name of an object as String.

For example:

public class Table{

public Long id = 1;

}

Table t = new Table();
String fieldName = getProperty(t.id); // return "id"


Keep in mind, I do not want to pass the string "id" anywhere in the code. I need it so if I change the variable "id" in the class, it changes it everywhere in the code. That's the purpose.

How can this be done?

Answer

I think it's what you want :

package stackOverflow;

import java.lang.reflect.Field;

public class Table
{
    public int id = 1;

    public static void main(String[] args) {
        Field[] fields = Table.class.getDeclaredFields();
        for (Field field : fields) {
            System.out.println(field.getName());
        }
    }
}

// => "id"

UPDATE #2:

If you want to be able to avoid using :

resultSet.getString("id")

because you'd have to change "id" everywhere in your code if you want another column name, you could define :

import java.util.HashMap;

public class columnName
{
    private static final HashMap<String, String> modifiedNames;

    static {
        modifiedNames = new HashMap<String, String>();
        modifiedNames.put("date", "new_date");
        // Add all the modified keys here...
    }

    public static String getName(String key) {
        if (modifiedNames.containsKey(key)) {
            return modifiedNames.get(key);
        } else {
            return key;
        }
    }
}

// System.out.println(columnName.getName("id"));    -> "id"
// System.out.println(columnName.getName("date"));  -> "new_date"

and use

resultSet.getString(columnName.getName("id"));

everywhere in your code.

If you need to change the string "id", you have to do it once for all your project.

If you don't want to change the column name, you don't have to write anything.

Comments