[英]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? 如果我有上述课程,是否可以使用反射列出由getter和setter定义的属性? I've tried the method below but it doesn't work,
Field[] fields
is left empty. 我尝试了下面的方法,但是它不起作用,
Field[] fields
保留为空。 I know I can do this in .Net but Java is a very different animal. 我知道我可以在.Net中做到这一点,但是Java是一种完全不同的动物。 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 ? 也许改用
cls.getDeclaredFields
吗? (And f.setAccessible(true)
before get private field). (和
f.setAccessible(true)
之前获取私有字段)。
If you want getter and setter you have to get method by getDeclaredMethods
. 如果需要getter和setter,则必须通过
getDeclaredMethods
获取方法。 Then I suggest using BeanUtils instead of writing your own reflection logic :) (IMHO less convenient is java.beans.Introspector ). 然后,我建议使用BeanUtils而不是编写自己的反射逻辑:)(恕我直言,不方便的是java.beans.Introspector )。
Use the Introspector class. 使用Introspector类。 Obtain the BeanInfo and use getPropertyDescriptors() method.
获取BeanInfo并使用getPropertyDescriptors()方法。 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
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.