我正在尝试获取对象的第一个父级的字段和值。我目前的代码是:
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获取。有没有办法做到这一点(使用反射,我不想实现其他方法)?
答案 0 :(得分:13)
Luchian,使用getSuperclass()方法获取对Class对象的引用,该对象表示相关对象的超类类型。在此之后,您可以轻松地以与示例相同的方式获取字段。
答案 1 :(得分:7)
创建方法
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.
}
}
答案 2 :(得分:0)
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);
}
}
答案 3 :(得分:-3)
您可以使用此代码从任何类中获取字段,而不是其父类或子类
for (Field field : YourClassName.class.getDeclaredFields()) {
//fields
}