简体   繁体   中英

Java Reflection - listing properties (getters & setters) of a class

public class foo
{
    private String _name;
    private String _bar;

    public String getName() {
        return _name;
    }

    public void setName(String name) {
        _name = name;
    }

    public String getBar() {
        return _bar;
    }

    public void setBarn(String bar) {
        _bar = bar;
    }
}

If I have the above class can I use reflection to list the properties defined by the getters and setters? I've tried the method below but it doesn't work, Field[] fields is left empty. I know I can do this in .Net but Java is a very different animal. Am I barking up the wrong tree altogether?

private HashMap<String, String> getHashMap(Object obj) {
    HashMap<String, String> map = new HashMap<String, String>();

    Class<?> cls = obj.getClass();

    Field fields[] = cls.getFields();
    for(Field f : fields) {
        String name = f.getName();
        String value = f.get(obj).toString();
        map.put(name, value);
    }
    return map;
}

Also setters and getters maybe evil, should I just drop this?

Maybe use cls.getDeclaredFields instead ? (And f.setAccessible(true) before get private field).

If you want getter and setter you have to get method by getDeclaredMethods . Then I suggest using BeanUtils instead of writing your own reflection logic :) (IMHO less convenient is java.beans.Introspector ).

Use the Introspector class. Obtain the BeanInfo and use getPropertyDescriptors() method. That should get you on the way.

You can do something like this:

List<Method> methods = Arrays.asList(getClass().getDeclaredMethods());
for (Method m : methods)
{
    String name = m.getName();
    if (name.startsWith("get") || name.startsWith("is"))
    {
        // Do something with the getter method
    } else if (name.startsWith("set"))
    {
        // Do something with the setter method
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM