com.societegenerale.commons.plugin.utils.ReflectionUtils Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of arch-unit-build-plugin-core Show documentation
Show all versions of arch-unit-build-plugin-core Show documentation
The core logic for Maven or Gradle ArchUnit plugin
package com.societegenerale.commons.plugin.utils;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class ReflectionUtils {
public static Class> loadClassWithContextClassLoader(String className) {
try {
return Thread.currentThread().getContextClassLoader().loadClass(className);
} catch (ClassNotFoundException e) {
throw ReflectionException.wrap(e);
}
}
public static T newInstance(Class clazz) {
try {
Constructor constructor = clazz.getDeclaredConstructor();
constructor.setAccessible(true);
return constructor.newInstance();
} catch (InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
throw ReflectionException.wrap(e);
}
}
// This will always be unsafe, so we might as well make it easier for the caller
@SuppressWarnings("unchecked")
public static T invoke(Method method, Object owner, Object... args) {
try {
method.setAccessible(true);
return (T) method.invoke(owner, args);
} catch (IllegalAccessException | InvocationTargetException e) {
throw ReflectionException.wrap(e);
}
}
// This will always be unsafe, so we might as well make it easier for the caller
@SuppressWarnings("unchecked")
public static T getValue(Field field, Object owner) {
try {
field.setAccessible(true);
return (T) field.get(owner);
} catch (IllegalAccessException e) {
throw ReflectionException.wrap(e);
}
}
}