我有一个类,我想找到它的所有公共字段(不是方法)。我该怎么做?
Field[] fields = YourClassName.class.getFields();
返回该类的所有公共变量的数组。
getFields()
返回整个类继承中的字段。如果您希望仅在相关类而不是其超类中定义字段,请使用 getDeclaredFields()
,并使用以下 public
方法过滤 Modifier
字段:
Modifier.isPublic(field.getModifiers());
YourClassName.class
文字实际上表示java.lang.Class
类型的对象。检查其文档以获取更多有趣的反射方法。
上面的
Field
类是java.lang.reflect.Field
。您可以看一下整个java.lang.reflect
包。
您可以根据需要使用两者中的任何一个:
Field[] fields = ClassName.class.getFields(); // returns inherited members but not private members.
Field[] fields = ClassName.class.getDeclaredFields(); // returns all members including private members but not inherited members.
要仅从上面的列表中过滤公共字段(根据要求),请使用以下代码:
List<Field> fieldList = Arrays.asList(fields).stream().filter(field -> Modifier.isPublic(field.getModifiers())).collect(
Collectors.toList());
正如一些用户提到的,下面的代码可以帮助查找给定类中的所有字段。
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<String,Object> props = m.convertValue(testObject, Map.class);
for(Map.Entry<String, Object> entry : props.entrySet()){
if(entry.getValue() instanceof String || entry.getValue() instanceof Integer || entry.getValue() instanceof Double){
System.out.println(entry.getKey() + "-->" + entry.getValue());
}
}
列表字段=Arrays.stream(reservation.class.getDeclaredFields()).map(Field::getName).toList();
它返回类内声明的所有成员的列表,包括私有成员。