JAVA8中可以通过java.lang.reflect.Parameter获取方法参数的名称:
package com.wlh.mybatis.proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.lang.reflect.Proxy;
import java.util.HashMap;
import java.util.Map;
public class ProxyTest {
public static void main(String[] args) {
IService iService = (IService) Proxy.newProxyInstance(ProxyTest.class.getClassLoader(), new Class<?>[]{IService.class}, new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
getMethodAsMap(method, args);
return null;
}
});
iService.doSomething(234, "name");
}
private static void getMethodAsMap(Method method, Object[] args) {
Map<String, Object> map = new HashMap<>();
Parameter[] parameters = method.getParameters();
for (int i = 0, len = parameters.length; i < len; i++) {
String name = parameters[i].getName();
Object value = args[i];
map.put(name, value);
}
System.out.println(map);
}
}
条件:
- JDK版本必须是1.8及以上
- 编译时:javac -parameters需要打开,默认是关闭的
- List item
IDEA开启 -parameters :