Last active
October 10, 2021 21:47
-
-
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
This file contains hidden or 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 <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