Utils/Reflect/src/main/java/eu/mikroskeem/utils/reflect/Reflect.java

125 lines
3.2 KiB
Java

package eu.mikroskeem.utils.reflect;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* Reflection utils
*
* @author Mark
*/
public class Reflect {
/**
* Find class by name
*
* @param clazz Class to search
* @return Class or null
*/
@Nullable
public static Class<?> getClass(@NotNull String clazz){
try {
return Class.forName(clazz);
} catch (ClassNotFoundException e){
return null;
}
}
/**
* Return whether class exists or not
*
* @param clazz Class to search
* @return Whether class existed or not
*/
public static boolean classExists(@NotNull String clazz){
return getClass(clazz) != null;
}
/**
* Get declared class method (public,protected,private)
*
* @param clazz Class to reflect
* @param method Method to search
* @param arguments Method arguments
* @return Method or null
*/
@Nullable
public static Method getMethod(@NotNull Class<?> clazz, @NotNull String method, Class<?>... arguments){
try {
Method m = clazz.getDeclaredMethod(method, arguments);
m.setAccessible(true);
return m;
} catch (NoSuchMethodException e){
return null;
}
}
/**
* Invoke method and get result
*
* @param method Method to invoke
* @param instance Instance where given method resides (null if static)
* @param args Method arguments
* @return Method result or null
*/
@Nullable
public static Object invokeMethod(@NotNull Method method, @Nullable Object instance, @Nullable Object... args){
try {
return method.invoke(instance, args);
} catch (IllegalAccessException|InvocationTargetException e){
return null;
}
}
/**
* Get declared class field (public,protected,private)
*
* @param clazz Class to reflect
* @param field Field to search
* @return Field or null
*/
@Nullable
public static Field getField(@NotNull Class<?> clazz, @NotNull String field){
try {
Field f = clazz.getDeclaredField(field);
f.setAccessible(true);
return f;
} catch (NoSuchFieldException e){
return null;
}
}
/**
* Read field
*
* @param field Field to read
* @param instance Instance where to read (null if static)
* @return Field contents or null;
*/
@Nullable
public static Object readField(@NotNull Field field, @Nullable Object instance){
try {
return field.get(instance);
} catch (IllegalAccessException e){
return null;
}
}
/**
* Write field
*
* @param field Field to write
* @param instance Instance where field resides (null if static)
* @param value Field new contents
*/
public static void writeField(@NotNull Field field, @Nullable Object instance, @Nullable Object value){
try {
field.set(instance, value);
} catch (IllegalAccessException e){}
}
}