我有一个使用文本文件(一个要求)的存储库类,这意味着我必须读取字符串并转换它们才能实例化对象.问题是我希望我的存储库类可以像我一样使用它,以便使用它来操作不同的对象类型.
那么,是否有一种(更优雅的)方法可以将字符串动态地转换为运行时所需的任何字段(基本)类型,同时避免大量的
try-catch结构有多个ifs / switch?
作为一个简短的简化版本,我希望objectA.txt只包含objectA的信息,类似于objectB.txt和我的Repository代码来处理两者:
存储库repoA =新存储库(“objectA.txt”,< A的类型列表>); TypeA a = repoA.getOne();
存储库repoB =新存储库(“objectB.txt”,< B的类型列表>); TypeB b = repoB.getOne();
是)我有的:
public class FileRepository extends InMemoryRepository{
private String fileName;
private List types;
public FileRepository(String fileName, List types) {
//@param types
// - list containing the Class to be instantiated followed by it's field types
super();
this.fileName = fileName;
this.types=types;
loadData();
}
private void loadData() {
Path path = Paths.get(fileName);
try {
Files.lines(path).forEach(line -> {
List items = Arrays.asList(line.split(","));
//create Class array for calling the correct constructor
Class[] cls=new Class[types.size()-1];
for (int i=1; i
cls[i-1]=types.get(i);
}
Constructor constr=null;
try {
//get the needed constructor
constr = types.get(0).getConstructor(cls);
} catch (NoSuchMethodException e) {
//do something
e.printStackTrace();
}
//here is where the fun begins
//@arg0 ... @argn are the primitives that need to be casted from string
//something like:
//*(type.get(1))* arg0=*(cast to types.get(1))* items.get(0);
//*(type.get(2))* arg1=*(cast to types.get(2))* items.get(1);
//...
Object obj= (Object) constr.newInstance(@arg0 ... @argn);
});
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
P.S.:我是JAVA的新手,所以请尽量简化解释.
解决方法:
没有IDE,所以我希望这是有道理的:
private static final Map> parsers = new HashMap<>();
static {
parsers.put(Long.class, Long::parseLong);
parsers.put(Integer.class, Integer::parseInt);
parsers.put(String.class, String::toString);
parsers.put(Double.class, Double::parseDouble);
parsers.put(Float.class, Float::parseFloat);
// add your own types here.
}
public T parse(Class klass, String value) {
// add some null-handling logic here? and empty values.
return (T)parsers.get(klass).apply(value);
}
然后,当您需要为构造函数创建参数时:
parameters =
IntStream
.range(0, cls.size-1)
.map(i -> (Object)parse(types.get(i), items.get(i)))
.toArray(Object[]::new);
标签:java,reflection
来源: https://codeday.me/bug/20190702/1355135.html