Question

I am browsing through methods in the class and then generate methods in another place with a different name - the parameters and return types are the same, I check them by method.getParameters(), method.isGeneric() etc.

So with a definition in original class like this:

public void fun1(T a, T b){ //something...}

I'd like to get:

public <T> void anotherName(T a, T b) { //something }

There is a relevant issue here which demontrates how to add < T> at the beginning of the class:Sun CodeModel generic method

JTypeVar t = checkedMethod.generify("T"); 
checkedMethod.param(jCodeModel.ref("LinkedList").narrow(t), "list");

However, I want to check all my methods in a loop and determine which of them have a generic type and therefore need a < T> before name. If I generify all methods, cases like this will appear:

public <String> String fun2(String a, String b);

and then it is unclear if I'd like to assign

String s = fun2("s","s");

Is there a way to check whether the given type is a known Java-type ?

Was it helpful?

Solution

Don't call "getParameters", use "getGenericParameterTypes". For your example, you will get an Array of two "Type" instances. Now "Type" can be

  • a Class (like String)
  • a ParameterizedType (= type containing Generics like List)
  • a TypeVariable (like "T")

you can loop the parameters and do "instanceof" to analyse which Type you are dealing with and then adopt your code.

Here is a very good blog on this topic: http://blog.vityuk.com/2011/03/java-generics-and-reflection.html

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top