public static void main(String[] args) {
new OwerMethodParam().test("bb")
}
public void test(String aa) {
Method[] methods = OwerMethodParam.class.getDeclaredMethods()//取得这个类的所有方法
if (methods != null) {
for (int i = 0i <methods.lengthi++) {
Method method = methods[i]
if ("test".equals(method.getName())) { //取得本方法,这个方法是test,所以就用test比较
Class<?>[] paramsClass = method.getParameterTypes()//取得参数列表的所有类
if (paramsClass != null) {
for (Class<?>class1 : paramsClass) {
System.out.println(class1.getName())
}
}
break
}
}
package testimport java.lang.reflect.Method
public class TTT {
public static void main(String[] args) {
Class c = Test.class
Method[] methods =c.getDeclaredMethods()
for (Method method : methods) {
System.out.print("方法的返回值"+method.getReturnType().getName())
System.out.print(" 方法名:"+method.getName()+"(")
Class[] paraTypes = method.getParameterTypes()
for (Class class1 : paraTypes) {
System.out.print("参数类型:"+class1.getSimpleName()+",")
}
System.out.println(")")
}
}
}
class Test
{
public void say(String word)
{
System.out.println(word)
}
public void say(String word,int n)
{
for(int i=0i<ni++){
System.out.println(word)
}
}
}
===============
方法的返回值void 方法名:say(参数类型:String,)
方法的返回值void 方法名:say(参数类型:String,参数类型:int,)
package com.mikan
import java.lang.annotation.*
/**
* @author Mikan
* @date 2015-08-04 23:39
*/
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Param {
String value()
}
获取注解中的参数名的工具类:
package com.mikan
import java.lang.annotation.Annotation
import java.lang.reflect.Method
/**
* @author Mikan
* @date 2015-08-05 00:26
*/
public class ParameterNameUtils {
/**
* 获取指定方法的参数名
*
* @param method 要获取参数名的方法
* @return 按参数顺序排列的参数名列表
*/
public static String[] getMethodParameterNamesByAnnotation(Method method) {
Annotation[][] parameterAnnotations = method.getParameterAnnotations()
if (parameterAnnotations == null || parameterAnnotations.length == 0) {
return null
}
String[] parameterNames = new String[parameterAnnotations.length]
int i = 0
for (Annotation[] parameterAnnotation : parameterAnnotations) {
for (Annotation annotation : parameterAnnotation) {
if (annotation instanceof Param) {
Param param = (Param) annotation
parameterNames[i++] = param.value()
}
}
}
return parameterNames
}
}
测试类:
package com.mikan
import java.lang.reflect.Method
import java.util.Arrays
/**
* @author Mikan
* @date 2015-08-04 23:40
*/
public class ParameterNameTest {
public void method1(@Param("parameter1") String param1, @Param("parameter2") String param2) {
System.out.println(param1 + param2)
}
public static void main(String[] args) throws Exception {
Class<ParameterNameTest> clazz = ParameterNameTest.class
Method method = clazz.getDeclaredMethod("method1", String.class, String.class)
String[] parameterNames = ParameterNameUtils.getMethodParameterNamesByAnnotation(method)
System.out.println(Arrays.toString(parameterNames))
}
}