Advertisement
Guest User

Untitled

a guest
Apr 6th, 2020
179
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.27 KB | None | 0 0
  1. import java.lang.reflect.*;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4.  
  5. public class InvokeDefault {
  6.  
  7.     public static <T> void invokeDefault (String className, String method) throws ClassNotFoundException, InvocationTargetException, IllegalAccessException, NoSuchMethodException, InstantiationException {
  8.         Class<?> clazz = Class.forName(className);
  9.         Method methodToInvoke = null;
  10.         boolean isMethodFound = false;
  11.  
  12.         //only works if no-parameter constructor exists, other option not implemented
  13.         Object dummy = clazz.getDeclaredConstructor().newInstance();
  14.  
  15.         Method[] declaredMethods = clazz.getDeclaredMethods();
  16.  
  17.         for(Method declaredMethod : declaredMethods){
  18.             if (declaredMethod.getName().equals(method)){
  19.                 declaredMethod.setAccessible(true);
  20.                 isMethodFound = true;
  21.                 methodToInvoke = declaredMethod;
  22.                 break;
  23.             }
  24.         }
  25.  
  26.         if(!isMethodFound){
  27.             for (Method declaredMethod : declaredMethods){
  28.                 if (declaredMethod.getName().equals("defaultMethod")){
  29.                     methodToInvoke = declaredMethod;
  30.                 }
  31.             }
  32.         }
  33.  
  34.         List<Parameter> defaultParameters = new ArrayList<>();
  35.  
  36.         if(isMethodFound){
  37.             Parameter[] parameters = methodToInvoke.getParameters();
  38.             for (Parameter parameter : parameters){
  39.                 if (!parameter.getType().isPrimitive()){
  40.                     Method[] objectMethods = parameter.getType().getDeclaredMethods();
  41.                     for (Method objectMethod : objectMethods){
  42.                         if (objectMethod.getName().equals("getDefaultValue") && Modifier.isStatic(objectMethod.getModifiers())){
  43.                             objectMethod.setAccessible(true);
  44.                             defaultParameters.add((Parameter) objectMethod.invoke(parameter.getClass()));
  45.                         }
  46.  
  47.                         else {
  48.                             defaultParameters.add(null);
  49.                         }
  50.                     }
  51.                 }
  52.             }
  53.         }
  54.  
  55.         if (methodToInvoke != null){
  56.             methodToInvoke.invoke(dummy, defaultParameters.toArray());
  57.         }
  58.     }
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement