Example usage for org.apache.commons.lang3.reflect MethodUtils invokeMethod

List of usage examples for org.apache.commons.lang3.reflect MethodUtils invokeMethod

Introduction

In this page you can find the example usage for org.apache.commons.lang3.reflect MethodUtils invokeMethod.

Prototype

public static Object invokeMethod(final Object object, final String methodName, Object[] args,
        Class<?>[] parameterTypes)
        throws NoSuchMethodException, IllegalAccessException, InvocationTargetException 

Source Link

Document

Invokes a named method whose parameter type matches the object type.

This method delegates the method search to #getMatchingAccessibleMethod(Class,String,Class[]) .

This method supports calls to methods taking primitive parameters via passing in wrapping classes.

Usage

From source file:atg.tools.dynunit.service.jdbc.InitializingDataSourceBase.java

/**
 * Get the driver manager connection used in this data source. This method is provided because the normal method
 * for accessing the database connection is package-local.
 *
 * @return underlying database connection object or {@code null} if it couldn't be found.
 *///from   w ww .j  a va  2 s  .  c o  m
@Nullable
public Connection getConnection() {
    try {
        return (Connection) MethodUtils.invokeMethod(this, "getDriverManagerConnection", null, null);
    } catch (NoSuchMethodException e) {
        logError(e);
    } catch (IllegalAccessException e) {
        logError(e);
    } catch (InvocationTargetException e) {
        logError(e);
    }
    return null;
}

From source file:com.offbynull.coroutines.instrumenter.asm.InstructionUtilsTest.java

@Test
public void mustCreateAndRunNestedSwitchStatements() throws Exception {
    // Augment signature
    methodNode.desc = Type.getMethodDescriptor(Type.getType(String.class),
            new Type[] { Type.INT_TYPE, Type.INT_TYPE });

    // Initialize variable table
    VariableTable varTable = new VariableTable(classNode, methodNode);
    Variable intVar1 = varTable.getArgument(1);
    Variable intVar2 = varTable.getArgument(2);

    // Update method logic
    /**//from   www.  j  a v  a 2 s .c  o  m
     * switch(arg1) {
     *    case 0:
     *        throw new RuntimeException("0");
     *    case 1:
     *         throw new RuntimeException("1");
     *    case 2:
     *         switch(arg2) {
     *             case 0:
     *                 throw new RuntimeException("0");
     *             case 1:
     *                 throw new RuntimeException("1");
     *             case 2:
     *                 return "OK!";
     *             default:
     *                 throw new RuntimeException("innerdefault")
     *         }
     *     default:
     *         throw new RuntimeException("default");
     * }
     */
    methodNode.instructions = tableSwitch(loadVar(intVar1), throwException("default"), 0, throwException("0"),
            throwException("1"),
            tableSwitch(loadVar(intVar2), throwException("innerdefault"), 0, throwException("inner0"),
                    throwException("inner1"),
                    InstructionUtils.returnValue(Type.getType(String.class), loadStringConst("OK!"))));

    // Write to JAR file + load up in classloader -- then execute tests
    try (URLClassLoader cl = createJarAndLoad(classNode)) {
        Object obj = cl.loadClass(STUB_CLASSNAME).newInstance();

        assertEquals("OK!", MethodUtils.invokeMethod(obj, STUB_METHOD_NAME, 2, 2));

        try {
            MethodUtils.invokeMethod(obj, STUB_METHOD_NAME, 0, 0);
            fail();
        } catch (InvocationTargetException ex) {
            assertEquals("0", ex.getCause().getMessage());
        }

        try {
            MethodUtils.invokeMethod(obj, STUB_METHOD_NAME, 2, 10);
            fail();
        } catch (InvocationTargetException ex) {
            assertEquals("innerdefault", ex.getCause().getMessage());
        }

        try {
            MethodUtils.invokeMethod(obj, STUB_METHOD_NAME, 10, 0);
            fail();
        } catch (InvocationTargetException ex) {
            assertEquals("default", ex.getCause().getMessage());
        }
    }
}

From source file:com.offbynull.coroutines.instrumenter.generators.GenericGeneratorsTest.java

@Test
public void mustCreateAndRunNestedSwitchStatements() throws Exception {
    // Augment signature
    methodNode.desc = Type.getMethodDescriptor(Type.getType(String.class),
            new Type[] { Type.INT_TYPE, Type.INT_TYPE });

    // Initialize variable table
    VariableTable varTable = new VariableTable(classNode, methodNode);
    Variable intVar1 = varTable.getArgument(1);
    Variable intVar2 = varTable.getArgument(2);

    // Update method logic
    /**/*from w  w w. jav a  2s.com*/
     * switch(arg1) {
     *    case 0:
     *        throw new RuntimeException("0");
     *    case 1:
     *         throw new RuntimeException("1");
     *    case 2:
     *         switch(arg2) {
     *             case 0:
     *                 throw new RuntimeException("0");
     *             case 1:
     *                 throw new RuntimeException("1");
     *             case 2:
     *                 return "OK!";
     *             default:
     *                 throw new RuntimeException("innerdefault")
     *         }
     *     default:
     *         throw new RuntimeException("default");
     * }
     */
    methodNode.instructions = tableSwitch(loadVar(intVar1), throwRuntimeException("default"), 0,
            throwRuntimeException("0"), throwRuntimeException("1"),
            tableSwitch(loadVar(intVar2), throwRuntimeException("innerdefault"), 0,
                    throwRuntimeException("inner0"), throwRuntimeException("inner1"),
                    GenericGenerators.returnValue(Type.getType(String.class), loadStringConst("OK!"))));

    // Write to JAR file + load up in classloader -- then execute tests
    try (URLClassLoader cl = createJarAndLoad(classNode)) {
        Object obj = cl.loadClass(STUB_CLASSNAME).newInstance();

        assertEquals("OK!", MethodUtils.invokeMethod(obj, STUB_METHOD_NAME, 2, 2));

        try {
            MethodUtils.invokeMethod(obj, STUB_METHOD_NAME, 0, 0);
            fail();
        } catch (InvocationTargetException ex) {
            assertEquals("0", ex.getCause().getMessage());
        }

        try {
            MethodUtils.invokeMethod(obj, STUB_METHOD_NAME, 2, 10);
            fail();
        } catch (InvocationTargetException ex) {
            assertEquals("innerdefault", ex.getCause().getMessage());
        }

        try {
            MethodUtils.invokeMethod(obj, STUB_METHOD_NAME, 10, 0);
            fail();
        } catch (InvocationTargetException ex) {
            assertEquals("default", ex.getCause().getMessage());
        }
    }
}

From source file:com.offbynull.coroutines.instrumenter.asm.InstructionUtilsTest.java

@Test
public void mustCreateAndRunIfStatements() throws Exception {
    // Augment signature
    methodNode.desc = Type.getMethodDescriptor(Type.getType(String.class),
            new Type[] { Type.INT_TYPE, Type.INT_TYPE });

    // Initialize variable table
    VariableTable varTable = new VariableTable(classNode, methodNode);
    Variable intVar1 = varTable.getArgument(1);
    Variable intVar2 = varTable.getArgument(2);

    // Update method logic
    /**/*from   www  . j  a  v a  2s  .c o  m*/
     * if (arg1 == arg2) {
     *     return "match";
     * }
     * return "nomatch";
     */
    methodNode.instructions = merge(
            ifIntegersEqual(loadVar(intVar1), loadVar(intVar2),
                    returnValue(Type.getType(String.class), loadStringConst("match"))),
            returnValue(Type.getType(String.class), loadStringConst("nomatch")));

    // Write to JAR file + load up in classloader -- then execute tests
    try (URLClassLoader cl = createJarAndLoad(classNode)) {
        Object obj = cl.loadClass(STUB_CLASSNAME).newInstance();

        assertEquals("match", MethodUtils.invokeMethod(obj, STUB_METHOD_NAME, 2, 2));
        assertEquals("nomatch", MethodUtils.invokeMethod(obj, STUB_METHOD_NAME, -2, 2));
        assertEquals("match", MethodUtils.invokeMethod(obj, STUB_METHOD_NAME, -2, -2));
    }
}

From source file:com.offbynull.coroutines.instrumenter.generators.GenericGeneratorsTest.java

@Test
public void mustCreateAndRunIfIntStatements() throws Exception {
    // Augment signature
    methodNode.desc = Type.getMethodDescriptor(Type.getType(String.class),
            new Type[] { Type.INT_TYPE, Type.INT_TYPE });

    // Initialize variable table
    VariableTable varTable = new VariableTable(classNode, methodNode);
    Variable intVar1 = varTable.getArgument(1);
    Variable intVar2 = varTable.getArgument(2);

    // Update method logic
    /**/*from www  .  j av a 2  s  . c  o  m*/
     * if (arg1 == arg2) {
     *     return "match";
     * }
     * return "nomatch";
     */
    methodNode.instructions = merge(
            ifIntegersEqual(loadVar(intVar1), loadVar(intVar2),
                    returnValue(Type.getType(String.class), loadStringConst("match"))),
            returnValue(Type.getType(String.class), loadStringConst("nomatch")));

    // Write to JAR file + load up in classloader -- then execute tests
    try (URLClassLoader cl = createJarAndLoad(classNode)) {
        Object obj = cl.loadClass(STUB_CLASSNAME).newInstance();

        assertEquals("match", MethodUtils.invokeMethod(obj, STUB_METHOD_NAME, 2, 2));
        assertEquals("nomatch", MethodUtils.invokeMethod(obj, STUB_METHOD_NAME, -2, 2));
        assertEquals("match", MethodUtils.invokeMethod(obj, STUB_METHOD_NAME, -2, -2));
    }
}

From source file:com.feilong.core.lang.reflect.MethodUtil.java

/**
 *  <code>object</code> ?? <code>methodName</code>.
 *
 * @param <T>//from  w  w  w.j a  v a2 s .  c om
 *            the generic type
 * @param object
 *            the object
 * @param methodName
 *            the method name
 * @param args
 *            the args
 * @param parameterTypes
 *            the parameter types
 * @return  <code>object</code> null, {@link NullPointerException}<br>
 *          <code>methodName</code> null, {@link NullPointerException}<br>
 *          <code>methodName</code> blank, {@link IllegalArgumentException}<br>
 * @see org.apache.commons.lang3.reflect.MethodUtils#invokeMethod(Object, String, Object[], Class[])
 * @since 1.1.1
 */
@SuppressWarnings("unchecked")
public static <T> T invokeMethod(final Object object, final String methodName, Object[] args,
        Class<?>[] parameterTypes) {
    Validate.notNull(object, "object can't be null!");
    Validate.notBlank(methodName, "methodName can't be blank!");
    try {
        return (T) MethodUtils.invokeMethod(object, methodName, args, parameterTypes);
    } catch (Exception e) {
        String pattern = "invokeMethod Exception,object:[{}],methodName:[{}],args:[{}],parameterTypes:[{}]";
        throw new ReflectException(Slf4jUtil.format(pattern, object, methodName, args, parameterTypes), e);
    }
}

From source file:com.offbynull.coroutines.instrumenter.generators.GenericGeneratorsTest.java

@Test
public void mustCreateAndRunIfObjectStatements() throws Exception {
    // Augment signature
    methodNode.desc = Type.getMethodDescriptor(Type.getType(String.class),
            new Type[] { Type.getType(Object.class), Type.getType(Object.class) });

    // Initialize variable table
    VariableTable varTable = new VariableTable(classNode, methodNode);
    Variable intVar1 = varTable.getArgument(1);
    Variable intVar2 = varTable.getArgument(2);

    // Update method logic
    /**//from   w  w  w  .ja v a 2  s.c  o  m
     * if (arg1 == arg2) {
     *     return "match";
     * }
     * return "nomatch";
     */
    methodNode.instructions = merge(
            ifObjectsEqual(loadVar(intVar1), loadVar(intVar2),
                    returnValue(Type.getType(String.class), loadStringConst("match"))),
            returnValue(Type.getType(String.class), loadStringConst("nomatch")));

    Object testObj1 = "test1";
    Object testObj2 = "test2";
    // Write to JAR file + load up in classloader -- then execute tests
    try (URLClassLoader cl = createJarAndLoad(classNode)) {
        Object obj = cl.loadClass(STUB_CLASSNAME).newInstance();

        assertEquals("match", MethodUtils.invokeMethod(obj, STUB_METHOD_NAME, testObj1, testObj1));
        assertEquals("nomatch", MethodUtils.invokeMethod(obj, STUB_METHOD_NAME, testObj1, testObj2));
        assertEquals("match", MethodUtils.invokeMethod(obj, STUB_METHOD_NAME, testObj2, testObj2));
    }
}

From source file:com.offbynull.coroutines.instrumenter.asm.InstructionUtilsTest.java

@Test
public void mustCreateAndRunForEachStatement() throws Exception {
    // Augment signature
    methodNode.desc = Type.getMethodDescriptor(Type.getType(String.class),
            new Type[] { Type.getType(Object[].class), Type.getType(Object.class) });
    methodNode.maxLocals += 2; // We've added 2 parameters to the method, and we need to upgrade maxLocals or else varTable will give
                               // us bad indexes for variables we grab with acquireExtra(). This is because VariableTable uses maxLocals
                               // to determine at what point to start adding extra local variables.

    // Initialize variable table
    VariableTable varTable = new VariableTable(classNode, methodNode);
    Variable objectArrVar = varTable.getArgument(1);
    Variable searchObjVar = varTable.getArgument(2);
    Variable counterVar = varTable.acquireExtra(Type.INT_TYPE);
    Variable arrayLenVar = varTable.acquireExtra(Type.INT_TYPE);
    Variable tempObjectVar = varTable.acquireExtra(Object.class);

    // Update method logic
    /**// w  w w. j  a va 2 s. co  m
     * for (Object[] o : arg1) {
     *     if (o == arg2) {
     *         return "match";
     *     }
     * }
     * return "nomatch";
     */
    methodNode.instructions = merge(
            forEach(counterVar, arrayLenVar, loadVar(objectArrVar),
                    merge(saveVar(tempObjectVar),
                            ifObjectsEqual(loadVar(tempObjectVar), loadVar(searchObjVar),
                                    returnValue(Type.getType(String.class), loadStringConst("match"))))),
            returnValue(Type.getType(String.class), loadStringConst("nomatch")));

    // Write to JAR file + load up in classloader -- then execute tests
    try (URLClassLoader cl = createJarAndLoad(classNode)) {
        Object obj = cl.loadClass(STUB_CLASSNAME).newInstance();

        Object o1 = new Object();
        Object o2 = new Object();
        Object o3 = new Object();

        assertEquals("match",
                MethodUtils.invokeMethod(obj, STUB_METHOD_NAME, (Object) new Object[] { o1, o2, o3 }, o1));
        assertEquals("match",
                MethodUtils.invokeMethod(obj, STUB_METHOD_NAME, (Object) new Object[] { o1, o2, o3 }, o2));
        assertEquals("match",
                MethodUtils.invokeMethod(obj, STUB_METHOD_NAME, (Object) new Object[] { o1, o2, o3 }, o3));
        assertEquals("nomatch",
                MethodUtils.invokeMethod(obj, STUB_METHOD_NAME, (Object) new Object[] { o1, o2, o3 }, null));
        assertEquals("nomatch", MethodUtils.invokeMethod(obj, STUB_METHOD_NAME,
                (Object) new Object[] { o1, o2, o3 }, new Object()));
    }
}

From source file:lineage2.gameserver.scripts.Scripts.java

/**
 * Method callScripts.//  w w w .j  av a 2  s.c  o m
 * @param caller Player
 * @param className String
 * @param methodName String
 * @param args Object[]
 * @param variables Map<String,Object>
 * @return Object
 */
public Object callScripts(Player caller, String className, String methodName, Object[] args,
        Map<String, Object> variables) {
    Object o;
    Class<?> clazz;

    clazz = _classes.get(className);
    if (clazz == null) {
        _log.error("Script class " + className + " not found!");
        return null;
    }

    try {
        o = clazz.newInstance();
    } catch (Exception e) {
        _log.error("Scripts: Failed creating instance of " + clazz.getName(), e);
        return null;
    }

    if ((variables != null) && !variables.isEmpty()) {
        for (Map.Entry<String, Object> param : variables.entrySet()) {
            try {
                FieldUtils.writeField(o, param.getKey(), param.getValue());
            } catch (Exception e) {
                _log.error("Scripts: Failed setting fields for " + clazz.getName(), e);
            }
        }
    }

    if (caller != null) {
        try {
            Field field = null;
            if ((field = FieldUtils.getField(clazz, "self")) != null) {
                FieldUtils.writeField(field, o, caller.getRef());
            }
        } catch (Exception e) {
            _log.error("Scripts: Failed setting field for " + clazz.getName(), e);
        }
    }

    Object ret = null;
    try {
        Class<?>[] parameterTypes = new Class<?>[args.length];
        for (int i = 0; i < args.length; i++) {
            parameterTypes[i] = args[i] != null ? args[i].getClass() : null;
        }

        ret = MethodUtils.invokeMethod(o, methodName, args, parameterTypes);
    } catch (NoSuchMethodException nsme) {
        _log.error("Scripts: No such method " + clazz.getName() + "." + methodName + "()!");
    } catch (InvocationTargetException ite) {
        _log.error("Scripts: Error while calling " + clazz.getName() + "." + methodName + "()",
                ite.getTargetException());
    } catch (Exception e) {
        _log.error("Scripts: Failed calling " + clazz.getName() + "." + methodName + "()", e);
    }

    return ret;
}