Yurii Shylov
Yurii Shylov

Reputation: 1217

Code generation: create interface for class

I'm writing a util to generate interface for class using Apache Velocity. Currently it uses the following 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
}

Here is the code used at the moment:

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);

The ????? should contain code to get a list of generics for the parameter and that is the problem, I still can't find a way to do that. I'm using the following test class:

public class TestDto {
  public void test(Map<Double, Integer> test) {
  }
}

How can I get this information? I've already tried ParameterizedType with no luck.

Update: the code above is now working.

Upvotes: 0

Views: 102

Answers (1)

Joop Eggen
Joop Eggen

Reputation: 109613

    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>

Because of type erasure, this still is generous information. Not heared from any push towards runtime generic type usage.

Upvotes: 1

Related Questions