Skip to content

Instantly share code, notes, and snippets.

@RutledgePaulV
Created February 2, 2016 03:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RutledgePaulV/aacdfada894e8bb23a37 to your computer and use it in GitHub Desktop.
Save RutledgePaulV/aacdfada894e8bb23a37 to your computer and use it in GitHub Desktop.
A generic instantiation method for java that determines the best constructor to use for the provided arguments.
public final class ObjectUtils {
private ObjectUtils() {
}
/**
* Instantiate a class for the provided constructor arguments.
*
* @param clazz The class to instantiate
*
* @param args The arguments for the constructor.
* The constructor used will be determined from the arguments provided.
*
* @return The new instance.
*/
public static <T> T init(Class<T> clazz, Object... args) {
try {
return (T) Arrays.stream(clazz.getConstructors())
.filter(construct -> Objects.equals(args.length, construct.getParameterCount()))
.filter(construct -> IntStream.range(0, construct.getParameterTypes().length)
.allMatch(val -> construct.getParameterTypes()[val].isAssignableFrom(args[val].getClass())))
.findFirst().orElseThrow(() -> new InstantiationException("Could not find compatible constructor."))
.newInstance(args);
} catch (InstantiationException | InvocationTargetException | IllegalAccessException e) {
throw new RuntimeException("Could not instantiate class for provided arguments.", e);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment