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



我正在读取对象及其子对象的所有字段值:

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[] {});
}

您应该根据每个字段的类型检查SomeInterface是否可赋值。类似于:

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

要读取带有反射的类的值,您可能需要使用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);
        }
    }
    

相关内容

  • 没有找到相关文章

最新更新