【发布时间】:2022-11-11 03:14:14
【问题描述】:
我创建了一个简单的转换器,它采用String fileName 并将.csv 文件中的行转换为List<Cat>。我现在面临的问题是现在还有一个Dog,并且我不允许复制和粘贴该方法以将返回类型更改为List<Dog>。
我尝试使用返回类型List<Object> 尝试在转换后将其解析为Cat 或Dog,但它不会让我这样做。如果可能的话,我正在寻找这个问题的通用解决方案。
我尝试了什么:
@Data
@Entity
@Table(name = "cat")
public class Cat implements Serializable {
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Id
@Column(columnDefinition = "int(10)", nullable = false)
int id;
@Column(columnDefinition = "varchar(20)", nullable = false)
String name;
}
@Data
@Entity
@Table(name = "dog")
public class Dog implements Serializable {
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Id
@Column(columnDefinition = "int(10)", nullable = false)
int id;
@Column(columnDefinition = "varchar(20)", nullable = false)
String name;
}
public List<Object> convertToObject(String fileName, String object) {
List<Object> objList = new ArrayList();
Path pathToFile = Paths.get(fileName);
try (BufferedReader br = Files.newBufferedReader(pathToFile)) {
int index = 1;
// read the first line from the text file
String line = br.readLine();
// loop until all lines are read
while (line != null) {
if (index > 1) {
switch (object) {
case "cat" : {
// use string.split to load a string array with the values from
// each line of
// the file, using a comma (,) as the delimiter
String[] attributes = line.split(",");
Cat cat = new Cat();
createCat(attributes, cat);
// adding Cat into ArrayList
objList.add(cat);
}
case "dog" : {
// use string.split to load a string array with the values from
// each line of
// the file, using a comma (,) as the delimiter
String[] attributes = line.split(",");
Dog dog = new Dog();
createDog(attributes, dog);
// adding Dog into ArrayList
objList.add(dog);
}
}
}
// read next line before looping
// if end of file reached, line would be null
line = br.readLine();
index++;
}
} catch (IOException ex) {
ex.printStackTrace(System.out);
}
return objList;
}
【问题讨论】:
-
我尝试使用返回类型 List<Object> 在转换后尝试将其解析为 Cat 或 Dog,但它不会让我这样做。到底发生了什么,它不编译吗?
-
@VitalyChura 似乎可以将 Cat 或 Dog 添加到 List<Object>,但之后无法解析为 List<Dog>。 “对象不能转换为狗”。
标签: java spring csv spring-mvc generics