正如少数用户所提到的,下面的代码可以帮助查找给定类中的所有字段。
TestClass testObject= new TestClass().getClass();
Method[] methods = testObject.getMethods();
for (Method method:methods)
{
String name=method.getName();
if(name.startsWith("get"))
{
System.out.println(name.substring(3));
}else if(name.startsWith("is"))
{
System.out.println(name.substring(2));
}
}
然而,更有趣的方法如下:
在Jackson库的帮助下,我能够找到String / integer / double类型的所有类属性,以及Map类中的相应值。 (不使用反射api!)
TestClass testObject = new TestClass();
com.fasterxml.jackson.databind.ObjectMapper m = new com.fasterxml.jackson.databind.ObjectMapper();
Map props = m.convertValue(testObject, Map.class);
for(Map.Entry entry : props.entrySet()){
if(entry.getValue() instanceof String || entry.getValue() instanceof Integer || entry.getValue() instanceof Double){
System.out.println(entry.getKey() + "-->" + entry.getValue());
}
}