So, I'm reading data from a file and depending on the text read, the program will use a constructor of the class that matches the parameters on the line. So the parameters given by the line of the text are stored into an ArrayList:
List<Object> parameters = new ArrayList<Object>();
Then I should somehow be able to create an object from those parameters, something like this:
constructor.newInstance(objects);
but I'm not quite sure how I could achieve that?
try {
Class<?> objectClass = Class.forName("com.editor.object." +line.substring(4, from+4));
Constructor[] allConstructors = objectClass.getDeclaredConstructors();
for(Constructor constructor : allConstructors){
Class<?>[] parameters = constructor.getParameterTypes();
if(objects.size() == parameters.length){
for(int i = 0; i < parameters.length; i++){
if(objects.get(i).getClass().equals(parameters[i])){
if(i + 1 == parameters.length){
return constructor.newInstance(objects); //<-- This doesen't work, I have no idea how should I call the "random" constructor?
}
}
}
}
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Edit 1: An example: I have the following line
new Platform(1, 1, 1, 1, 1);
-> Would create a new Platform object with parameters given. The referred class and constructor might be pretty much anything, so I can't rely on stuff like that. Of course I could just run that in code but I would like to learn more and that's why I won't do it the easiest way.
Activator.createInstance()might be useful.parameters[i].isAssignableFrom(objects.get(i).getClass())instead ofequals, since you don't necessarily need the exact same class.constructor.newInstance(objects.toArray()). You are currently effectively invokingctor.newInstance(new Object[] { objects }).