Instantiate a class without default constructor
If a Java class does not have a default constructor, it cannot be instantiated. Easy solution (using Google Guava 11 to speed things up):
private final Cache constructorCache = CacheBuilder.newBuilder()
.build(new CacheLoader() {
final ReflectionFactory reflectionFactory = ReflectionFactory.getReflectionFactory();
@Override
public Constructor load(Class type) throws Exception {
return reflectionFactory.newConstructorForSerialization(type, Object.class.getDeclaredConstructor(new Class[0]));
}
});
public Object newInstance(Class type) throws Exception {
Constructor customConstructor;
try {
customConstructor = constructorCache.get(type);
} catch (ExecutionException e) {
throw Throwables.propagate(e.getCause());
}
return customConstructor.newInstance(new Object[0]);
}
Enjoy!