2013-08-16 63 views
0

我正在编写一个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没有运气。

更新:上面的代码现在正在工作。

回答

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> 

由于类型擦除,这仍然是慷慨的信息。没有听到任何推向运行时泛型类型的使用。

+0

非常好!对我来说,主要的问题是让泛型类将它们添加到导入列表中。我忘记了我们可以使用像java.util.blablabla这样的完整路径。此外,简单的类有一个小问题,因为它返回“java.util.String类”。目前我正在使用'paramDescriptor.setType(method.getGenericParameterTypes()[i] .toString()。replace(“class”,“”))''。不是很优雅,但很有效。我必须检查这是否适合返回类型,之后,我会解答答案。 –