PandaLib/pandalib-reflect/src/main/java/fr/pandacube/lib/reflect/Reflect.java

52 lines
1.7 KiB
Java
Raw Normal View History

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.
*/
@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.
*/
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 objects class.
* @throws IllegalArgumentException if {@code instance} is null.
*/
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());
}
}