Created
February 2, 2016 03:33
-
-
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.
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
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