集册 Java实例教程 使用指定的参数在调用对象上调用方法。

使用指定的参数在调用对象上调用方法。

欢马劈雪     最近更新时间:2020-01-02 10:19:05

520
使用指定的参数在调用对象上调用方法。


//package com.nowjava;

import java.lang.reflect.InvocationTargetException;

import java.lang.reflect.Method;/**from nowjava - 时  代  Java**/


public class Main {

    public static void main(String[] argv) throws Exception {

        Object invokingObject = "nowjava.com";

        String methodNameToInvoke = "nowjava.com";

        Object args = "nowjava.com";

        System.out.println(invokePrivateMethod(invokingObject,

                methodNameToInvoke, args));

    }


    /**

     * Invoke a method on an invoking object with the specified arguments. I.e.,

     * ((type)invokingObject).methodNameToInvoke (arguments);

     * 

     * @param type

     *            allows method calls based on a supertype of invokingObject

     * @param invokingObject

     *            may be null if calling a static method

     * @param methodNameToInvoke

     * @param args

     * @return the result from invoking the method or null if unsuccessful

     * @throws IllegalArgumentException

     * @throws IllegalAccessException

     * @throws InvocationTargetException

     * @throws NoSuchMethodException

     */

    public static Object invokePrivateMethod(Class<?> type,

            Object invokingObject, String methodNameToInvoke,/*来自 时代Java公众号 - N o w J a  v a . c o m*/

            Object... args) throws IllegalArgumentException,

            IllegalAccessException, InvocationTargetException,

            NoSuchMethodException {

        Method[] methods = type.getDeclaredMethods();

        for (Method method : methods) {

            String methodName = method.getName();

            if (methodName.equals(methodNameToInvoke)) {

                Object result = method.invoke(invokingObject, args);

                return (result);

            }

        }

        throw new NoSuchMethodException("Method " + methodNameToInvoke

                + " not found.");

    }


    /**

     * Invoke a method on an invoking object with the specified arguments. I.e.,

     * invokingObject.methodNameToInvoke (arguments);

     * 

     * @param invokingObject

     *            may be null if calling a static method

     * @param methodNameToInvoke

     * @param args

     * @return the result from invoking the method or null if unsuccessful

     * @throws IllegalArgumentException

     * @throws IllegalAccessException

     * @throws InvocationTargetException

     * @throws NoSuchMethodException

     */

    public 
展开阅读全文