personthecat.catlib.util.unsafe.CachingReflectionHelper Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of catlib-quilt Show documentation
Show all versions of catlib-quilt Show documentation
Utilities for serialization, commands, noise generation, IO, and some new data types.
The newest version!
package personthecat.catlib.util.unsafe;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import static personthecat.catlib.util.Shorthand.f;
@SuppressWarnings("unused")
public class CachingReflectionHelper {
private static final Map, Object> INSTANCE_MAP = new ConcurrentHashMap<>();
@SuppressWarnings("unchecked")
public static T tryInstantiate(final Class c) {
return (T) INSTANCE_MAP.computeIfAbsent(c, k -> constructWithoutArgs(c));
}
@SuppressWarnings("unchecked")
public static T dispose(final Class type) {
return (T) INSTANCE_MAP.remove(type);
}
private static T constructWithoutArgs(final Class c) {
for (final Constructor> constructor : c.getDeclaredConstructors()) {
if (constructor.getParameterCount() == 0) {
constructor.setAccessible(true);
return tryInvoke(c, constructor);
}
}
throw new UncheckedReflectiveAccessException("Missing no arg constructor: ", c);
}
@SuppressWarnings("unchecked")
private static T tryInvoke(final Class c, final Constructor> constructor) {
try {
return (T) constructor.newInstance();
} catch (final IllegalAccessException | InvocationTargetException | InstantiationException ignored) {
throw new UncheckedReflectiveAccessException("Could not instantiate: {}", c.getSimpleName());
}
}
private static class UncheckedReflectiveAccessException extends RuntimeException {
UncheckedReflectiveAccessException(final String s, final Object... args) {
super(f(s, args));
}
}
}