Skip to content

Instantly share code, notes, and snippets.

@bfu4
Last active October 10, 2021 21:47
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bfu4/1b600b1b6a1c188cee705df02efa664a to your computer and use it in GitHub Desktop.
Save bfu4/1b600b1b6a1c188cee705df02efa664a to your computer and use it in GitHub Desktop.
aids way to construct an object from a class and argument type fuck box types fr
public <T> T makeObject(Class<T> clazz, Object... args) throws NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException {
Class<?>[] types = Arrays.stream(args).map(cls -> getPrimitiveType(cls.getClass())).toArray(Class[]::new);
Constructor<T> constr = getConstructor(clazz, types);
constr.setAccessible(true);
return constr.newInstance(args);
}
@SuppressWarnings("unchecked")
public <T> Constructor<T> getConstructor(Class<T> clazz, Class<?>... types) {
return (Constructor<T>) Arrays.stream(clazz.getDeclaredConstructors())
.filter(constructor -> Arrays.equals(map(constructor.getParameterTypes()), types))
.findAny()
.orElse(null);
}
public Class<?>[] map(final Class<?>... types) {
return Arrays.stream(types).map(ReflectionTest::getPrimitiveType).toArray(Class[]::new);
}
private static Class<?> getPrimitiveType(final Class<?> clazz) {
Class<?>[] boxed = {Integer.class, Float.class, Double.class, Short.class, Byte.class, Boolean.class};
return Arrays.stream(boxed).filter(box -> {
if (box == clazz) {
try {
Field field = box.getField("TYPE");
return field.get(null) != null;
} catch (NoSuchFieldException | IllegalAccessException e) {
return false;
}
}
return true;
}).findAny().orElse(clazz);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment