torsdag 20 oktober 2011

Create instance of class with no public constructor

private T instantiateEscenicObject(Class type, Map fields) throws InstantiationException {
T instance = null;
Constructor[] constructors = type.getDeclaredConstructors();

for (int i = 0; i < constructors.length; i++) {
Constructor constructor = constructors[i];
try {
constructor.setAccessible(Boolean.TRUE);
instance = (T) constructor.newInstance();
break;
} catch (Exception e) {
}
}

if (instance == null) {
throw new InstantiationException("Could not instantiate class " + type.getName());
}

for (String key : fields.keySet()) {
ReflectionTestUtils.setField(instance, key, fields.get(key));
}

return instance;
}