2022-07-20 13:18:57 +02:00
|
|
|
|
package fr.pandacube.lib.reflect;
|
2022-01-22 20:48:12 +01:00
|
|
|
|
|
|
|
|
|
import java.util.Collections;
|
|
|
|
|
import java.util.HashMap;
|
|
|
|
|
import java.util.Map;
|
|
|
|
|
|
2022-07-28 01:05:35 +02:00
|
|
|
|
/**
|
|
|
|
|
* Provides methods to get instances of {@link ReflectClass}.
|
|
|
|
|
*/
|
2022-01-22 20:48:12 +01:00
|
|
|
|
public class Reflect {
|
|
|
|
|
|
|
|
|
|
|
2022-07-28 01:05:35 +02:00
|
|
|
|
private static final Map<Class<?>, ReflectClass<?>> classCache = Collections.synchronizedMap(new HashMap<>());
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Wraps the provided class into a {@link ReflectClass}.
|
|
|
|
|
* @param clazz the class to wrap.
|
|
|
|
|
* @param <T> the type of the class.
|
|
|
|
|
* @return a {@link ReflectClass} wrapping the provided class.
|
|
|
|
|
*/
|
2022-01-30 23:07:51 +01:00
|
|
|
|
@SuppressWarnings("unchecked")
|
|
|
|
|
public static <T> ReflectClass<T> ofClass(Class<T> clazz) {
|
|
|
|
|
return (ReflectClass<T>) classCache.computeIfAbsent(clazz, ReflectClass::new);
|
2022-01-22 20:48:12 +01:00
|
|
|
|
}
|
2022-07-28 01:05:35 +02:00
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Wraps the provided class into a {@link ReflectClass}.
|
|
|
|
|
* @param className the name of the class, passed into {@link Class#forName(String)} before using
|
|
|
|
|
* {@link #ofClass(Class)}.
|
|
|
|
|
* @return a {@link ReflectClass} wrapping the provided class.
|
|
|
|
|
* @throws ClassNotFoundException if the provided class was not found.
|
|
|
|
|
*/
|
2022-01-30 23:07:51 +01:00
|
|
|
|
public static ReflectClass<?> ofClass(String className) throws ClassNotFoundException {
|
2022-01-22 20:48:12 +01:00
|
|
|
|
return ofClass(Class.forName(className));
|
|
|
|
|
}
|
2022-07-28 01:05:35 +02:00
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Wraps the class of the provided object into a {@link ReflectClass}.
|
|
|
|
|
* @param instance the object wrom which to get the class using {@link Object#getClass()}.
|
|
|
|
|
* @return a {@link ReflectClass} wrapping the provided object’s class.
|
|
|
|
|
* @throws IllegalArgumentException if {@code instance} is null.
|
|
|
|
|
*/
|
2022-01-30 23:07:51 +01:00
|
|
|
|
public static ReflectClass<?> ofClassOfInstance(Object instance) {
|
2022-01-22 20:48:12 +01:00
|
|
|
|
if (instance == null)
|
|
|
|
|
throw new IllegalArgumentException("instance can't be null");
|
|
|
|
|
return ofClass(instance.getClass());
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
}
|