Home > Java > javaTutorial > Java example of obtaining the parameter type of a reflection method based on the method name

Java example of obtaining the parameter type of a reflection method based on the method name

高洛峰
Release: 2017-01-22 10:39:46
Original
1444 people have browsed 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(),"方法名称"));
Copy after login

For more java examples of obtaining the parameter type of a reflection method based on the method name, please pay attention to the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template