Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package me.rehabcz.testfx.base;
- import java.lang.reflect.InvocationTargetException;
- import java.lang.reflect.Method;
- /**
- * Utility class for working with reflections
- * @author rehabcz
- */
- public class ReflectionUtils {
- /**
- * Invokes class method without direct instance of class
- * @param obj Class reference
- * @param methodName Name of referenced method
- * @param params Parameter to pass in referenced method
- * @return Result of invoked method
- */
- public static Object invokeMethod(Class<?> obj, String methodName, Object...params) {
- int paramCount = params.length;
- Method method;
- Object requiredObj = null;
- Class<?>[] classArray = new Class <?>[paramCount];
- for (int i = 0; i < paramCount; i++) {
- classArray[i] = params[i].getClass();
- }
- try {
- Object o = obj.getDeclaredConstructor().newInstance();
- method = o.getClass().getDeclaredMethod(methodName, classArray);
- method.setAccessible(true);
- requiredObj = method.invoke(o, params);
- } catch (InstantiationException | NoSuchMethodException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
- e.printStackTrace();
- }
- return requiredObj;
- }
- /**
- * Invokes class method using existing object instance
- * @param obj Object instance
- * @param methodName Name of referenced method
- * @param params Parameter to pass in referenced method
- * @return Result of invoked method
- */
- public static Object invokeMethod(Object obj, String methodName, Object...params) {
- int paramCount = params.length;
- Method method;
- Object requiredObj = null;
- Class<?>[] classArray = new Class <?>[paramCount];
- for (int i = 0; i < paramCount; i++) {
- classArray[i] = params[i].getClass();
- }
- try {
- method = obj.getClass().getDeclaredMethod(methodName, classArray);
- method.setAccessible(true);
- requiredObj = method.invoke(obj, params);
- } catch (NoSuchMethodException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
- e.printStackTrace();
- }
- return requiredObj;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement