简书链接:多参反射的调用封装
文章字数:111,阅读全文大约需要1分钟
做一个ReflectUtil.callMethod(method,arg)的万能调用需要解决基本类型问题,如果直接传递intvalue,会被变成了包装类型。所以这里进行了下样板代码处理。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
|
import java.lang.reflect.Method;
public class MainTest { public static void call(int a){ System.out.println("call(int):"+a); } public static void call(Integer a){ System.out.println("call(integer):"+a); } public static void call(long a){ System.out.println("call(long):"+a); } public static void call(Long a){ System.out.println("call(Long):"+a); } public static Class<?>[] getParameterTypes(Object... args) { Class<?>[] clazzes = new Class<?>[args.length]; for (int i = 0; i < args.length; i++) { Object obj = args[i]; if(obj!=null){ if(obj instanceof PrimitiveValue){ PrimitiveValue baseTypeValue = (PrimitiveValue) obj; clazzes[i]=baseTypeValue.type; }else{ clazzes[i] = obj.getClass(); }
} } return clazzes; } public static Object[] getParameterValue(Object... args) {
for (int i = 0; i < args.length; i++) { Object obj = args[i]; if(obj!=null){ if(obj instanceof PrimitiveValue){ PrimitiveValue baseTypeValue = (PrimitiveValue) obj; args[i]=baseTypeValue.value; }
} } return args; }
public static class PrimitiveValue { public Class type; public Object value;
public PrimitiveValue(int value) { this.value = value; type=int.class; } public PrimitiveValue(long value) { this.value = value; type=long.class; } public PrimitiveValue(short value) { this.value = value; type=short.class; } public PrimitiveValue(byte value) { this.value = value; type=byte.class; } public PrimitiveValue(float value) { this.value = value; type=float.class; } public PrimitiveValue(double value) { this.value = value; type=double.class; } public PrimitiveValue(boolean value) { this.value = value; type=boolean.class; }
}
public static void executeMethod(Object... test1){ Class<?>[] args = getParameterTypes(test1); try { //java.lang.NoSuchMethodException: MainTest.call(java.lang.Integer) Method method = MainTest.class.getMethod("call", args); method.invoke(null,getParameterValue(test1)); } catch (Throwable e) { e.printStackTrace(); } }
public static void main(String[] args) { //call1(Integer.valueOf(1)); executeMethod(new PrimitiveValue(1)); executeMethod(123); executeMethod(new PrimitiveValue(1111l));// call(long) executeMethod(111L);
}
}
|
输出结果
1 2 3 4 5
| call(int):1 call(integer):123 call(long):1111 call(Long):111
|