Created
February 25, 2014 15:57
-
-
Save ocirne23/9211748 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
where did you find this?