Skip to content

Instantly share code, notes, and snippets.

@ocirne23
Created February 25, 2014 15:57
Show Gist options
  • Save ocirne23/9211748 to your computer and use it in GitHub Desktop.
Save ocirne23/9211748 to your computer and use it in GitHub Desktop.
private static <T> T createNewInstance(Class<T> type) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
Constructor<?>[] constructors = type.getDeclaredConstructors();
// if its an interface or abstract class
if (constructors.length == 0)
return null;
// if trying to create a generic
if (type == Class.class)
return null;
for (Constructor<?> c : constructors) {
if (c.getParameterTypes().length == 0) {
c.setAccessible(true);
return (T) c.newInstance();
}
}
Constructor<?> c = constructors[0];
Class<?>[] parameters = c.getParameterTypes();
Object[] params = new Object[parameters.length];
for (int i = 0; i < parameters.length; i++) {
if (parameters[i].isPrimitive()) {
if (parameters[i] == char.class)
params[i] = '0';
else if (parameters[i] == boolean.class)
params[i] = false;
else if (parameters[i] == short.class)
params[i] = (short) 0;
else if (parameters[i] == byte.class)
params[i] = (byte) 0;
else
params[i] = 0;
} else {
params[i] = null;
}
}
c.setAccessible(true);
return (T) c.newInstance(params);
}
@NimbusBP1729
Copy link

where did you find this?

@ocirne23
Copy link
Author

wrote it myself .-.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment