我正在实现一个Utility方法,它接受String作为参数并转换为具有泛型的对象。我可以使用下面的代码实现,但弱点是每个需要解析的对象必须有一个字符串构造函数。无法定义对象必须具有String构造函数。有没有其他更好的方法来实现这一点通过使用多态或泛型?
AAA.java
public class AAA {
private String id;
private String description;
public AAA(String str) {
// Do parsing...
}
效用方法。
public static <T extends Base> List<T> readFile(File file, Class<T> type) {
List<T> collection = new ArrayList<T>();
// Read file line by line and convert to Instance
Constructor<T> ctor = type.getConstructor(String.class);
T newInstance = ctor.newInstance(line);
if (newInstance != null) {
collection.add(newInstance);
}
return collection;
}
用法:
List<AAA> list = FileUtil.readFile(file, AAA.class);
答案 0 :(得分:0)
我假设您的POJO类(实际包含数据的类)通常采用您示例中的格式。意味着所有字段都是String
值。如果不是这种情况,我的解决方案需要进行一些改进。
我的建议是对您描述的用例使用反射。我过去一直非常成功。虽然如果应用不好,反思可能会造成严重的性能损失。
解析代码看起来大致如下。我省略了一个方法标题,因为你提供的标题看起来很好。我提供的代码将假设在String[]
变量line
中我们找到了已经解析过的CSV文件行。数组的每个元素都包含一行CSV行。
String[] line; // initialised as explained above
T newInstance = T.newInstance(); // invoke default constructor
Field[] fields = newInstance.getClass().getDeclaredFields(); // use reflection to read all fields
int count = 0;
for(Fields f : fields) {
f.set(newInstance, line[count]);
count++;
}
免责声明:以上代码不进行任何边界检查!假设CSV行和类中的字段数具有相同的长度!
在Field
对象上,我通常也会调用getAnnotation
来检查字段上是否设置了某个注释。这允许您编写类似的类:
public class AAAAnnotated {
@MyCSVAnnotation
String field1;
@MyCSVAnnotation
String field2;
String field3;
}
如果您的代码检查字段是否使用注释进行注释,您甚至可以在POJO类中控制哪些字段要加载表格CSV以及哪些字段保持不变。