Java 反射调用动态方法

package com.pigetest.util;

import java.lang.reflect.Method;


public class PrivateMethodTestHelper {
    public static Object invoke(String clazzName,String methodName,Object...params){
        try {
            Class<?> clazz=Class.forName(clazzName);
            Object obj=clazz.newInstance();
            Method[] methods = clazz.getDeclaredMethods();
            Method callMethod=null;
            for(Method method:methods){
                if(method.getName().equals(methodName)){
                    callMethod=method;
                    break;
                }
            }
            callMethod.setAccessible(true);
            return (Object) callMethod.invoke(obj,params);


        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }



    public static void main(String[] args) {
        int value=(Integer) PrivateMethodTestHelper.invoke("com.pigetest.util.AddNumber","addNumber",1,2);
        System.out.println(value);
    }

}

 

posted @ 2016-06-29 20:11  程序猿进化之路  阅读(4363)  评论(0编辑  收藏  举报