public class CsvReader {
public <T> T format(T obj, String line) throws IntrospectionException, InvocationTargetException, IllegalAccessException, InstantiationException {
line = "admin|男";
String[] values = line.split("\\|");
Object newInstance = obj.getClass().newInstance();
Field[] fields = newInstance.getClass().getDeclaredFields();
for(Field f : fields) {
CsvColumn annotation = f.getAnnotation(CsvColumn.class);
PropertyDescriptor pd = new PropertyDescriptor(f.getName(), UserBean.class);
Method wM = pd.getWriteMethod();//获得写方法
wM.invoke(newInstance, values[annotation.value()]);//因为知道是int类型的属性,所以传个int过去就是了。。实际情况中需要判断下他的参数类型
}
return (T)newInstance;
}
public <T> T format(Class<T> clazz, String line) throws IntrospectionException, InvocationTargetException, IllegalAccessException, InstantiationException {
line = "admin|男";
String[] values = line.split("\\|");
Object newInstance = clazz.newInstance();
Field[] fields = newInstance.getClass().getDeclaredFields();
for(Field f : fields) {
CsvColumn annotation = f.getAnnotation(CsvColumn.class);
PropertyDescriptor pd = new PropertyDescriptor(f.getName(), UserBean.class);
Method wM = pd.getWriteMethod();//获得写方法
wM.invoke(newInstance, values[annotation.value()]);//因为知道是int类型的属性,所以传个int过去就是了。。实际情况中需要判断下他的参数类型
}
return (T)newInstance;
}
}
package com.reige.sparksql;
import java.util.List;
import java.util.function.Function;
public class UserBean implements CsvLineResolver {
@CsvColumn(0)
private String name;
@CsvColumn(1)
private String sex;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
@Override
public String toString() {
return "UserBean{" +
"name='" + name + '\'' +
", sex='" + sex + '\'' +
'}';
}
@Override
public void resolve(List<String> values) {
System.out.println(values);
}
class Test implements Function<Object, String> {
@Override
public String apply(Object o) {
return null;
}
}
}
@Documented
@Target(ElementType.FIELD)
@Inherited
@Retention(RetentionPolicy.RUNTIME )
public @interface CsvColumn {
int value();
}