有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

我将接受一个csv文件,它将具有特定的值。这些值将根据对象的属性进行验证

例如:

如果有一个person类包含姓名、电子邮件、电话号码等

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

set();
get();
}

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


共 (2) 个答案

  1. # 1 楼答案

    使用反射,可以看到类中有哪些字段:

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

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

  2. # 2 楼答案

    我通常采用这种解决方案。它是一个谓词,因此可以重用。取决于您可以在guava或Apache Commons集合中使用哪个谓词

    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;
        }
    }