有没有办法在Java中提取数组中对象的所有属性名称

时间:2013-03-21 20:50:46

标签: java csv

我将接受一个具有特定值的csv文件。这些值将再次验证对象的属性

示例:

如果有人类有姓名,电子邮件,电话号码等。

public class Person{
private String name;
private String email;
private String status;

set();
get();
}

并且csv文件有“name”,“email”,我想编写一个验证逻辑,它将根据对象属性检查csv的内容。

2 个答案:

答案 0 :(得分:1)

使用反射,您可以看到班级中的哪些字段:

Field[] fields = Person.class.getDeclaredFields();
for(Field curField:fields)
{
    System.out.println(curField.getName());
}

然后,您可以从csv中获取字段名称并比较其值。

答案 1 :(得分:0)

我通常会使用此解决方案。这是一个谓词,所以它是可重用的。取决于您使用哪个谓词,您可以将它与guava或Apache Commons Collections一起使用。

public class BeanPropertyPredicate<T, V> implements Predicate<T> {

    // Logger
    private static final Logger log = LoggerFactory.getLogger(BeanPropertyPredicate.class);

    public enum Comparison {EQUAL, NOT_EQUAL}
    private final String propertyName;
    private final Collection<V> values;
    private final Comparison comparison;

    public BeanPropertyPredicate(String propertyName, Collection<V> values, Comparison comparison) {
        this.propertyName = propertyName;
        this.values = values;
        this.comparison = comparison;
    }

    @Override
    public boolean apply(@Nullable T input) {

        try {

            PropertyDescriptor propertyDescriptor = PropertyUtils.getPropertyDescriptor(input, propertyName);
            Object value = propertyDescriptor.getReadMethod().invoke(input);

            switch (comparison) {
                case EQUAL:
                    if(!values.contains(value))  {
                        return false;
                    }
                    break;
                case NOT_EQUAL:
                    if(values.contains(value))  {
                        return false;
                    }
                    break;
            }

        } catch (Exception e) {
            log.error("Failed to access property {}", propertyName, e);
        }

        return true;
    }
}
相关问题