Advertisement
RehabCZ

Java Reflection Method Invoke

Jan 23rd, 2024 (edited)
602
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.33 KB | Source Code | 0 0
  1. package me.rehabcz.testfx.base;
  2.  
  3. import java.lang.reflect.InvocationTargetException;
  4. import java.lang.reflect.Method;
  5.  
  6. /**
  7.  * Utility class for working with reflections
  8.  * @author rehabcz
  9.  */
  10. public class ReflectionUtils {
  11.  
  12.     /**
  13.      * Invokes class method without direct instance of class
  14.      * @param obj Class reference
  15.      * @param methodName Name of referenced method
  16.      * @param params Parameter to pass in referenced method
  17.      * @return Result of invoked method
  18.      */
  19.     public static Object invokeMethod(Class<?> obj, String methodName, Object...params) {
  20.         int paramCount = params.length;
  21.         Method method;
  22.         Object requiredObj = null;
  23.         Class<?>[] classArray = new Class <?>[paramCount];
  24.         for (int i = 0; i < paramCount; i++) {
  25.             classArray[i] = params[i].getClass();
  26.         }
  27.         try {
  28.             Object o = obj.getDeclaredConstructor().newInstance();
  29.             method = o.getClass().getDeclaredMethod(methodName, classArray);
  30.             method.setAccessible(true);
  31.             requiredObj = method.invoke(o, params);
  32.         } catch (InstantiationException | NoSuchMethodException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
  33.             e.printStackTrace();
  34.         }
  35.  
  36.         return requiredObj;
  37.     }
  38.  
  39.     /**
  40.      * Invokes class method using existing object instance
  41.      * @param obj Object instance
  42.      * @param methodName Name of referenced method
  43.      * @param params Parameter to pass in referenced method
  44.      * @return Result of invoked method
  45.      */
  46.     public static Object invokeMethod(Object obj, String methodName, Object...params) {
  47.         int paramCount = params.length;
  48.         Method method;
  49.         Object requiredObj = null;
  50.         Class<?>[] classArray = new Class <?>[paramCount];
  51.         for (int i = 0; i < paramCount; i++) {
  52.             classArray[i] = params[i].getClass();
  53.         }
  54.         try {
  55.             method = obj.getClass().getDeclaredMethod(methodName, classArray);
  56.             method.setAccessible(true);
  57.             requiredObj = method.invoke(obj, params);
  58.         } catch (NoSuchMethodException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
  59.             e.printStackTrace();
  60.         }
  61.  
  62.         return requiredObj;
  63.     }
  64. }
  65.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement