我正在编写一个util来使用Apache Velocity为类生成接口。目前它使用以下dtos:
public class ClassDescriptor {
private String name;
private List<MethodDescriptor> methods;
// getters/setters
}
public class MethodDescriptor {
private String name;
private String returnType;
private List<ParamDescriptor> parameters;
// getters/setters
}
public class ParamDescriptor {
public String name;
public String type;
public List<String> generics;
// getters/setters
}
以下是目前使用的代码:
final Class<?> clazz;
final ClassDescriptor classDescriptor = new ClassDescriptor();
final List<MethodDescriptor> methodDescriptors = new ArrayList<MethodDescriptor>();
for (Method method : clazz.getDeclaredMethods()) {
final MethodDescriptor methodDescriptor = new MethodDescriptor();
final Paranamer paranamer = new AdaptiveParanamer();
final String[] parameterNames = paranamer.lookupParameterNames(method, false);
final List<ParamDescriptor> paramDescriptors = new ArrayList<ParamDescriptor>();
for (int i = 0; i < method.getParameterTypes().length; i++) {
final ParamDescriptor paramDescriptor = new ParamDescriptor();
paramDescriptor.setName(parameterNames[i]);
paramDescriptors.add(paramDescriptor);
paramDescriptor.setType(method.getGenericParameterTypes()[i].toString().replace("class ", ""));
}
methodDescriptor.setParameters(paramDescriptors);
methodDescriptor.setName(method.getName());
methodDescriptor.setReturnType(method.getGenericReturnType().toString());
methodDescriptors.add(methodDescriptor);
}
classDescriptor.setMethods(methodDescriptors);
classDescriptor.setName(simpleName);
?????应该包含代码来获取参数的泛型列表,这就是问题,我仍然找不到这样做的方法。我正在使用以下测试类:
public class TestDto {
public void test(Map<Double, Integer> test) {
}
}
如何获取此信息?我已经尝试ParameterizedType
但没有运气。
更新:上面的代码正在运行。
答案 0 :(得分:1)
Class<TestDto> klazz = TestDto.class;
try {
Method method = klazz.getDeclaredMethod("test", Map.class);
Type type = method.getGenericParameterTypes()[0];
System.out.println("Type: " + type);
} catch (NoSuchMethodException ex) {
Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex);
} catch (SecurityException ex) {
Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex);
}
Type: java.util.Map<java.lang.Double, java.lang.Integer>
由于类型擦除,这仍然是慷慨的信息。没有听到任何推动运行时泛型类型的使用。