我试图获得我的对象的第一个父的字段和值。我现在的代码是这样的:
Class<? extends Object> cls = obj.getClass();
Field[] fields = cls.getDeclaredFields();
for ( Field field : fields )
{
String fieldName = field.getName();
String fieldValue = field.get(obj);
}
我的类结构类似于:
class A
{
int x;
}
class B extends A
{
int y;
}
class C extends B
{
int z;
}
现在,我传递一个C对象的方法,我想从C和B获得所有字段,但不是从a。有办法做到这一点(使用反射,我不想实现其他方法)?
Luchian,使用getSuperclass()方法获取对class对象的引用,该对象表示所讨论对象的超类类型。在此之后,您将很容易获得字段,就像您在示例中所做的那样。
创建方法
public static void printFieldsFor(Class cls, Object obj) {
Field[] fields = cls.getDeclaredFields();
for ( Field field : fields ) {
String fieldName = field.getName();
String fieldValue = field.get(obj);
}
}
printFieldsFor(object.getClass(), obj);
printFieldsFor(object.getClass().getSuperclass(), obj);
或使用循环
for(Class cls = object.getClass();
cls!=null && cls!=A.class;
cls = cls.getSuperclass()) {
for(Field field : cls.getDeclaredFields()) {
String fieldName = field.getName();
String fieldValue = field.get(obj);
// do something with the field.
}
}
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* @author pablo.barbosa (2017-08-15)
*/
public class ReflectionUtil {
/**
* Hiding constructor. The methods are statics
*/
private ReflectionUtil() {
// Hiding constructor
}
public static List<Field> getInheritedDeclaredFields(Class<?> fromClass, Class<?> stopWhenClass) {
if (stopWhenClass == null) {
stopWhenClass = Object.class;
}
List<Field> fields = new ArrayList<>();
List<Class<?>> classes = new ArrayList<>();
Class<?> cls = fromClass;
do {
classes.add(cls);
cls = cls.getSuperclass();
} while (cls != null && !cls.equals(stopWhenClass));
for (int i = classes.size() - 1; i >= 0; i--) {
fields.addAll(Arrays.asList(classes.get(i).getDeclaredFields()));
}
return fields;
}
public static Field getInheritedDeclaredField(Class<?> fromClass, String fieldName, Class<?> stopWhenClass) throws NoSuchFieldException {
if (stopWhenClass == null) {
stopWhenClass = Object.class;
}
Class<?> cls = fromClass;
do {
Field field;
try {
field = cls.getDeclaredField(fieldName);
if (field != null) {
return field;
}
} catch (NoSuchFieldException | SecurityException e) {
// Nothing. We'll try to get field from superclass
}
cls = cls.getSuperclass();
} while (cls != null && !cls.equals(stopWhenClass));
// If we got here, we'll throw an exception
throw new NoSuchFieldException(fieldName);
}
public static Object getInheritedDeclaredFieldValue(Object obj, String fieldName, Class<?> stopWhenClass) throws NoSuchFieldException, IllegalAccessException {
Field field = getInheritedDeclaredField(obj.getClass(), fieldName, stopWhenClass);
field.setAccessible(true);
return field.get(obj);
}
}
您可以使用此代码简单地从任何类获取字段,无论它的父类或子类
for (Field field : YourClassName.class.getDeclaredFields()) {
//fields
}