java中的反射问题
样本类
Class Question{
public int a ( String a, char[] c,int b) { return b; }
}
通过反射获取具有名称和参数的方法的方法
public Method getMethodWithParams(Class<?> klasa, String methodName, Class<?>[] params) throws
SecurityException, NoSuchMethodException {
Class<?>[] primitivesToWrappers =
ClassUtils.primitivesToWrappers(params);
Method publicMethod = MethodUtils.getMatchingAccessibleMethod(klasa,
methodName,
primitivesToWrappers );
System.out.println(publicMethod.toGenericString());
return publicMethod;
}
private void printParams(Type[] types) throws ClassNotFoundException {
for (Type genericParameterType : types) {
System.out.println(genericParameterType.toString());
}
}
主程序
Question cls = new Question();
Class<?>[] paramString = new Class<?>[3];
paramString[0] = String.class;
paramString[1] = char[].class;
paramString[2] = int.class;
Method methodParams1 = getMethodParams(cls.getClass(),"a", paramString);
System.out.println(methodParams1.getName());
Type[] genericTypes = methodParams1.getParameterTypes();
printParams(genericTypes);
输出是:
一种
类 java.lang.String
类[C
整数
问题是下一个测试失败
Character testCharacterObjArray = new Character[]
Class<?> aClass = ClassUtils.getClass("[C", true);
Assert.assertEquals(testCharacterObjArray.getClass(), aClass);
ClassUtils 来自 org.apache.commons.lang3
寻找一个库来获取“[Ljava.lang.Character;” 而不是“[C”,因为它似乎 ClassUtils.primitivesToWrappers() 失败。
基于stephen的解决方案:
public Class<?> convertStringToClass(String str) throws
ClassNotFoundException {
Class<?> aClass = ClassUtils.getClass(str, true);
if (aClass.isArray()) {
Class<?> primitiveToWrapper =
ClassUtils.primitiveToWrapper(aClass.getComponentType());
Object newInstance = Array.newInstance(primitiveToWrapper, 0);
System.out.println("****" + newInstance.getClass().getName());
return ClassUtils.
getClass(newInstance.getClass().getName(), true);
}
else {
return ClassUtils.primitiveToWrapper(aClass);
}
}