I have a repository class that uses text files (requirement), which means I have to read lines and do them to create objects. The problem is that I want my repository class to be generic, how can I do this to use it to manage different types of objects.
So, is there a (more elegant) way to dynamically translate strings to any type (primitive) type that it needs at run time, while avoiding a lot of try-catch structures with multiple ifs / switch?
As a short simplified version, I want objectA.txt to contain only objectA information, similarly for objectB.txt and my repository code to handle both:
Repository repo A = new repository ("objectA.txt", <type list for A>); Type A a = repoA.getOne ();
Repo repository B = new repository ("objectB.txt", <type list for B>); Type B b = repoB.getOne ();
What I have:
public class FileRepository extends InMemoryRepository{
private String fileName;
private List<Class> types;
public FileRepository(String fileName, List<Class> types) {
super();
this.fileName = fileName;
this.types=types;
loadData();
}
private void loadData() {
Path path = Paths.get(fileName);
try {
Files.lines(path).forEach(line -> {
List<String> items = Arrays.asList(line.split(","));
Class[] cls=new Class[types.size()-1];
for (int i=1; i<types.size(); i++){
cls[i-1]=types.get(i);
}
Constructor constr=null;
try {
constr = types.get(0).getConstructor(cls);
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
Object obj= (Object) constr.newInstance(@arg0 ... @argn);
});
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
PS: I am new to JAVA, so please keep the explanations as simple as possible.
source
share