Java Code Examples for org.apache.commons.lang3.reflect.MethodUtils#getAccessibleMethod()

The following examples show how to use org.apache.commons.lang3.reflect.MethodUtils#getAccessibleMethod() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: LinkCellClickListener.java    From cuba with Apache License 2.0 6 votes vote down vote up
protected Method findLinkInvokeMethod(Class cls, String methodName) {
    Method exactMethod = MethodUtils.getAccessibleMethod(cls, methodName, Entity.class, String.class);
    if (exactMethod != null) {
        return exactMethod;
    }

    // search through all methods
    Method[] methods = cls.getMethods();
    for (Method availableMethod : methods) {
        if (availableMethod.getName().equals(methodName)) {
            if (availableMethod.getParameterCount() == 2
                    && Void.TYPE.equals(availableMethod.getReturnType())) {
                if (Entity.class.isAssignableFrom(availableMethod.getParameterTypes()[0]) &&
                        String.class == availableMethod.getParameterTypes()[1]) {
                    // get accessible version of method
                    return MethodUtils.getAccessibleMethod(availableMethod);
                }
            }
        }
    }
    return null;
}
 
Example 2
Source File: DeclarativeColumnGenerator.java    From cuba with Apache License 2.0 6 votes vote down vote up
@Nullable
protected Method findGeneratorMethod(Class cls, String methodName) {
    Method exactMethod = MethodUtils.getAccessibleMethod(cls, methodName, Entity.class);
    if (exactMethod != null) {
        return exactMethod;
    }

    // search through all methods
    Method[] methods = cls.getMethods();
    for (Method availableMethod : methods) {
        if (availableMethod.getName().equals(methodName)) {
            if (availableMethod.getParameterCount() == 1
                    && Component.class.isAssignableFrom(availableMethod.getReturnType())) {
                if (Entity.class.isAssignableFrom(availableMethod.getParameterTypes()[0])) {
                    // get accessible version of method
                    return MethodUtils.getAccessibleMethod(availableMethod);
                }
            }
        }
    }
    return null;
}
 
Example 3
Source File: AbstractObjectToStringConverter.java    From yarg with Apache License 2.0 6 votes vote down vote up
protected Object convertFromStringUnresolved(Class<?> parameterClass, String paramValueStr) {
    try {
        Constructor constructor = ConstructorUtils.getAccessibleConstructor(parameterClass, String.class);
        if (constructor != null) {
            return constructor.newInstance(paramValueStr);
        } else {
            Method valueOf = MethodUtils.getAccessibleMethod(parameterClass, "valueOf", String.class);
            if (valueOf != null) {
                return valueOf.invoke(null, paramValueStr);
            }
        }
    } catch (ReflectiveOperationException e) {
        throw new ReportingException(
                String.format("Could not instantiate object with class [%s] from [%s] string.",
                        parameterClass.getCanonicalName(),
                        paramValueStr));
    }
    return paramValueStr;
}
 
Example 4
Source File: LuVTierEnhancer.java    From bartworks with MIT License 5 votes vote down vote up
private static void addDreamcraftItemListItems(Collection LuVMachines){
    try {
        Class customItemListClass = Class.forName("com.dreammaster.gthandler.CustomItemList");
        Method hasnotBeenSet = MethodUtils.getAccessibleMethod(customItemListClass, "hasBeenSet");
        Method get = MethodUtils.getAccessibleMethod(customItemListClass, "get", long.class, Object[].class);
        for (Enum customItemList : (Enum[]) FieldUtils.getField(customItemListClass, "$VALUES", true).get(null)) {
            if (customItemList.toString().contains("LuV") && (boolean) hasnotBeenSet.invoke(customItemList))
                LuVMachines.add((ItemStack) get.invoke(customItemList, 1, new Object[0]));
        }
    } catch (IllegalAccessException | ClassNotFoundException | InvocationTargetException e) {
        e.printStackTrace();
    }
}
 
Example 5
Source File: ParameterValidatorFilterTest.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
  new Expectations() {
    {
      operation.getProducerInstance();
      result = new Controller();

      operation.getProducerMethod();
      result = MethodUtils.getAccessibleMethod(Controller.class, "op", String.class, Model.class);

      invocation.toProducerArguments();
      result = new Object[] {null, new Model()};
    }
  };
}
 
Example 6
Source File: WekaUtil.java    From AILibs with GNU Affero General Public License v3.0 5 votes vote down vote up
public static Classifier cloneClassifier(final Classifier c) throws Exception {
	Method cloneMethod = MethodUtils.getAccessibleMethod(c.getClass(), "clone");
	if (cloneMethod != null) {
		return (Classifier) cloneMethod.invoke(c);
	}
	return AbstractClassifier.makeCopy(c);
}
 
Example 7
Source File: EumnUtil.java    From HA-DB with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
static <T> String getInvokeValue(T t, String methodName) {
	try {
		Method method = MethodUtils.getAccessibleMethod(t.getClass(),
				methodName);
		String text = TransformUtils.toString(method.invoke(t));
		return text;
	} catch (Exception e) {
		return null;
	}
}
 
Example 8
Source File: MenuItemCommands.java    From cuba with Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
    userActionsLog.trace("Menu item {} triggered", item.getId());

    StopWatch sw = createStopWatch(item);

    Object beanInstance = beanLocator.get(bean);
    try {
        Method methodWithParams = MethodUtils.getAccessibleMethod(beanInstance.getClass(), beanMethod, Map.class);
        if (methodWithParams != null) {
            methodWithParams.invoke(beanInstance, params);
            return;
        }

        Method methodWithScreen = MethodUtils.getAccessibleMethod(beanInstance.getClass(), beanMethod, FrameOwner.class);
        if (methodWithScreen != null) {
            methodWithScreen.invoke(beanInstance, origin);
            return;
        }

        MethodUtils.invokeMethod(beanInstance, beanMethod, (Object[]) null);
    } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
        throw new RuntimeException("Unable to execute bean method", e);
    }

    sw.stop();
}
 
Example 9
Source File: FieldGroupTest.java    From cuba with Apache License 2.0 5 votes vote down vote up
protected Object getComposition(FieldGroup.FieldConfig fc) {
    Method getCompositionMethod = MethodUtils.getAccessibleMethod(fc.getClass(), "getComponent");
    Object composition;
    try {
        composition = getCompositionMethod.invoke(fc);
    } catch (IllegalAccessException | InvocationTargetException e) {
        throw new RuntimeException("Invoke error", e);
    }
    return ((Component) composition).unwrap(Object.class);
}
 
Example 10
Source File: SimpleClassWriterTest.java    From coroutines with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Test
public void testCustomGetCommonSuperClassImplementation() throws Exception {
    // augment method to take in a single int argument
    methodNode.desc = Type.getMethodDescriptor(Type.VOID_TYPE, Type.INT_TYPE);
    
    
    // augment method instructions
    VariableTable varTable = new VariableTable(classNode, methodNode);
    
    Class<?> iterableClass = Iterable.class;
    Constructor arrayListConstructor = ConstructorUtils.getAccessibleConstructor(ArrayList.class);
    Constructor linkedListConstructor = ConstructorUtils.getAccessibleConstructor(LinkedList.class);
    Constructor hashSetConstructor = ConstructorUtils.getAccessibleConstructor(HashSet.class);
    Method iteratorMethod = MethodUtils.getAccessibleMethod(iterableClass, "iterator");
    
    Type iterableType = Type.getType(iterableClass);
    
    Variable testArg = varTable.getArgument(1);
    Variable listVar = varTable.acquireExtra(iterableType);
    
    /**
     * Collection it;
     * switch(arg1) {
     *     case 0:
     *         it = new ArrayList()
     *         break;
     *     case 1:
     *         it = new LinkedList()
     *         break;
     *     case 2:
     *         it = new HashSet()
     *         break;
     *     default: throw new RuntimeException("must be 0 or 1");
     * }
     * list.iterator();
     */
    LabelNode invokePoint = new LabelNode();
    InsnList methodInsnList
            = merge(tableSwitch(loadVar(testArg),
                            throwRuntimeException("must be 0 or 1"),
                            0,
                            merge(
                                    construct(arrayListConstructor),
                                    saveVar(listVar),
                                    jumpTo(invokePoint)
                            ),
                            merge(
                                    construct(linkedListConstructor),
                                    saveVar(listVar),
                                    jumpTo(invokePoint)
                            ),
                            merge(
                                    construct(hashSetConstructor),
                                    saveVar(listVar),
                                    jumpTo(invokePoint)
                            )
                    ),
                    addLabel(invokePoint),
                    call(iteratorMethod, GenericGenerators.loadVar(listVar)),
                    pop(), // discard results of call
                    returnVoid()
            );
    
    methodNode.instructions = methodInsnList;
    
    
    // attemp to write out class -- since we're branching like this it should call getCommonSuperClass() with the types specified in
    // each of the switch cases. getCommonsuperClass() is the logic we explictly override and are testing. createJarAndLoad uses
    // simpleclasswriter
    try (URLClassLoader cl = createJarAndLoad(classNode)) {
        Object obj = cl.loadClass("SimpleStub").newInstance();
        
        // there should not be any verifer errors here
        MethodUtils.invokeMethod(obj, "fillMeIn", 0);
        MethodUtils.invokeMethod(obj, "fillMeIn", 1);
        MethodUtils.invokeMethod(obj, "fillMeIn", 2);
    }
}
 
Example 11
Source File: SimpleVerifierTest.java    From coroutines with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Test
public void testVertificationWithoutUsingClassLoader() throws Exception {

    // augment method to take in a single int argument
    methodNode.desc = Type.getMethodDescriptor(Type.VOID_TYPE, Type.INT_TYPE);

    // augment method instructions
    VariableTable varTable = new VariableTable(classNode, methodNode);

    Class<?> iterableClass = Iterable.class;
    Constructor arrayListConstructor = ConstructorUtils.getAccessibleConstructor(ArrayList.class);
    Constructor linkedListConstructor = ConstructorUtils.getAccessibleConstructor(LinkedList.class);
    Constructor hashSetConstructor = ConstructorUtils.getAccessibleConstructor(HashSet.class);
    Method iteratorMethod = MethodUtils.getAccessibleMethod(iterableClass, "iterator");

    Type iterableType = Type.getType(iterableClass);

    VariableTable.Variable testArg = varTable.getArgument(1);
    VariableTable.Variable listVar = varTable.acquireExtra(iterableType);

    /**
     * Collection it;
     * switch(arg1) {
     *     case 0:
     *         it = new ArrayList()
     *         break;
     *     case 1:
     *         it = new LinkedList()
     *         break;
     *     case 2:
     *         it = new HashSet()
     *         break;
     *     default: throw new RuntimeException("must be 0 or 1");
     * }
     * list.iterator();
     */
    LabelNode invokePoint = new LabelNode();
    InsnList methodInsnList
            = merge(tableSwitch(loadVar(testArg),
                            throwRuntimeException("must be 0 or 1"),
                            0,
                            merge(
                                    construct(arrayListConstructor),
                                    saveVar(listVar),
                                    jumpTo(invokePoint)
                            ),
                            merge(
                                    construct(linkedListConstructor),
                                    saveVar(listVar),
                                    jumpTo(invokePoint)
                            ),
                            merge(
                                    construct(hashSetConstructor),
                                    saveVar(listVar),
                                    jumpTo(invokePoint)
                            )
                    ),
                    addLabel(invokePoint),
                    call(iteratorMethod, loadVar(listVar)),
                    pop(), // discard results of call
                    returnVoid()
            );

    methodNode.instructions = methodInsnList;
    
    
    
    // write out class and read it back in again so maxes and frames can be properly computed for frame analyzer
    SimpleClassWriter writer = new SimpleClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS, classRepo);
    classNode.accept(writer);
    byte[] data = writer.toByteArray();
    
    ClassReader cr = new ClassReader(data);
    classNode = new SimpleClassNode();
    cr.accept(classNode, 0);

    
    methodNode = classNode.methods.get(1);
    

    // analyze
    Frame<BasicValue>[] frames;
    try {
        frames = new Analyzer<>(new SimpleVerifier(classRepo)).analyze(classNode.name, methodNode);
    } catch (AnalyzerException ae) {
        throw new IllegalArgumentException("Analyzer failed to analyze method", ae);
    }
    
    
    // get last frame
    Frame frame = frames[frames.length - 1];
    BasicValue basicValue = (BasicValue) frame.getLocal(listVar.getIndex());
    
    
    // ensure that that the local variable for the collection we created in the switch blocks is an abstract type
    assertEquals("java/util/AbstractCollection", basicValue.getType().getInternalName());
}
 
Example 12
Source File: EventUtils.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
private boolean hasMatchingParametersMethod(final Method method)
{
    return MethodUtils.getAccessibleMethod(target.getClass(), methodName, method.getParameterTypes()) != null;
}
 
Example 13
Source File: EventUtils.java    From astor with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Checks whether a method for the passed in parameters can be found.
 *
 * @param method the listener method invoked
 * @return a flag whether the parameters could be matched
 */
private boolean hasMatchingParametersMethod(final Method method) {
    return MethodUtils.getAccessibleMethod(target.getClass(), methodName, method.getParameterTypes()) != null;
}
 
Example 14
Source File: EventUtils.java    From astor with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Checks whether a method for the passed in parameters can be found.
 *
 * @param method the listener method invoked
 * @return a flag whether the parameters could be matched
 */
private boolean hasMatchingParametersMethod(final Method method) {
    return MethodUtils.getAccessibleMethod(target.getClass(), methodName, method.getParameterTypes()) != null;
}
 
Example 15
Source File: EventUtils.java    From astor with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Checks whether a method for the passed in parameters can be found.
 *
 * @param method the listener method invoked
 * @return a flag whether the parameters could be matched
 */
private boolean hasMatchingParametersMethod(final Method method) {
    return MethodUtils.getAccessibleMethod(target.getClass(), methodName, method.getParameterTypes()) != null;
}