当前位置: 移动技术网 > IT编程>开发语言>Java > java根据方法名称取得反射方法的参数类型示例

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

2019年07月22日  | 移动技术网IT编程  | 我要评论


复制代码 代码如下:

/**
 * 根据方法名称取得反射方法的参数类型(没有考虑同名重载方法使用时注意)
 * @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(),"方法名称"));

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网