如何从使用反射实现接口的类的字段中获取值?

时间:2015-11-18 09:30:32

标签: java reflection

我正在读取一个物体及其子女的所有字段值:

private List<Object> getAllFieldsValues(Class<?> clazz, String[] filter) throws IllegalArgumentException, IllegalAccessException {
    List<Object> fieldsValues = new ArrayList<>();
    Field[] fields = clazz.getDeclaredFields();

    for (Field field : fields) {

        // some code

        if (field.getType().isInterface()) {
            // get all fields from a class which implements the interface
        }
    }
    return fieldsValues;
}

我需要从实现接口的类中获取所有值。怎么样?

编辑: 我的目标是获取所有字段值以生成一些哈希:

public class HashGen<T extends Layout> {    
    public String hash(T layout, String[] filter) throws IllegalArgumentException, IllegalAccessException {
        Class<?> current = layout.getClass();

        List<Object> fieldValues = new ArrayList<>();
        while (!current.getName().equals("Object")) {
            fieldValues.addAll(getAllFieldsValues(current, filter));
            current = current.getSuperclass();
        }

        return generateHashFromValues(fieldValues);
    }
}

我的班级结构的例子:

public interface SomeInterface { }

public class SomeClass implements SomeInterface { 
    private int someField;

    // get / set
}


public interface Layout { }

public interface X540 extends Layout { }

public class X540Impl implements X540 { 
    private int id;
    private SomeInterface;

    // get / set
}


public static void main(String[] args) {
    X540 x540 = new X540Impl();
    x540.setId(1);

    SomeInterface someInterface = new SomeClass();
    someInterface.setSomeField(5454);

    x540.setSomeInterface(someInterface);

    // i need to generate an hash of all fields values of X540Impl and SomeClass because X540Impl has a SomeClass
    String hash = new HashGen().hash(x540, new String[] {});

}

2 个答案:

答案 0 :(得分:0)

您应该检查SomeInterface是否可以从每个字段的类型中分配。类似的东西:

if (SomeInterface.class.isAssignableFrom(field.getType())) { ... } 

答案 1 :(得分:0)

要使用反射读取类的值,您可能希望使用Apache的BeanUtils库,这样可以节省一些代码。

以下示例执行了两项可能有用的内容

  1. 确定传递的对象是否实现了接口

  2. 如何使用反射从对象获取值。

    // obj = the object not the object.class
    if (obj instanceof SomeInterface) {
        for (Field field : obj.getClass().getDeclaredFields()) {
            Object value = BeanUtils.getProperty(obj, field.getName());
            System.out.println(field.getName() + "=" + value);
        }
    }