Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.lang.reflect.*;
- import java.util.ArrayList;
- import java.util.List;
- public class InvokeDefault {
- public static <T> void invokeDefault (String className, String method) throws ClassNotFoundException, InvocationTargetException, IllegalAccessException, NoSuchMethodException, InstantiationException {
- Class<?> clazz = Class.forName(className);
- Method methodToInvoke = null;
- boolean isMethodFound = false;
- //only works if no-parameter constructor exists, other option not implemented
- Object dummy = clazz.getDeclaredConstructor().newInstance();
- Method[] declaredMethods = clazz.getDeclaredMethods();
- for(Method declaredMethod : declaredMethods){
- if (declaredMethod.getName().equals(method)){
- declaredMethod.setAccessible(true);
- isMethodFound = true;
- methodToInvoke = declaredMethod;
- break;
- }
- }
- if(!isMethodFound){
- for (Method declaredMethod : declaredMethods){
- if (declaredMethod.getName().equals("defaultMethod")){
- methodToInvoke = declaredMethod;
- }
- }
- }
- List<Parameter> defaultParameters = new ArrayList<>();
- if(isMethodFound){
- Parameter[] parameters = methodToInvoke.getParameters();
- for (Parameter parameter : parameters){
- if (!parameter.getType().isPrimitive()){
- Method[] objectMethods = parameter.getType().getDeclaredMethods();
- for (Method objectMethod : objectMethods){
- if (objectMethod.getName().equals("getDefaultValue") && Modifier.isStatic(objectMethod.getModifiers())){
- objectMethod.setAccessible(true);
- defaultParameters.add((Parameter) objectMethod.invoke(parameter.getClass()));
- }
- else {
- defaultParameters.add(null);
- }
- }
- }
- }
- }
- if (methodToInvoke != null){
- methodToInvoke.invoke(dummy, defaultParameters.toArray());
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement