欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java根据方法名称取得反射方法的参数类型示例

程序员文章站 2024-02-22 17:07:04
复制代码 代码如下:/** * 根据方法名称取得反射方法的参数类型(没有考虑同名重载方法使用时注意) * @param obj  &...


复制代码 代码如下:

/**
 * 根据方法名称取得反射方法的参数类型(没有考虑同名重载方法使用时注意)
 * @param obj         类实例 
 * @param methodname  方法名
 * @return
 * @throws classnotfoundexception
 */
public static class[]  getmethodparamtypes(object classinstance,
 string methodname) throws classnotfoundexception{
 class[] paramtypes = null;
   method[]  methods = classinstance.getclass().getmethods();//全部方法
 for (int  i = 0;  i< methods.length; i++) {
     if(methodname.equals(methods[i].getname())){//和传入方法名匹配
         class[] params = methods[i].getparametertypes();
            paramtypes = new class[ params.length] ;
            for (int j = 0; j < params.length; j++) {
                paramtypes[j] = class.forname(params[j].getname());
            }
            break;
        }
    }
 return paramtypes;
}

 //取得方法测试(test类大家还是任意写吧,这里不列举了)
 method m =  test.class.newinstance().getclass().getdeclaredmethod("方法名称", getmethodparamtypes(test.class.newinstance(),"方法名称"));