Consider this contrived class:
import java.util.List;
public class Test {
public String chooseRandom(List<String> strings) {
return null;
}
}
When using reflection to test this method, how can I get an object Classrepresenting java.lang.String(or even a string "java.lang.String") while looking at the arguments for chooseRandom?
I know that Java erases types at compile time, but they should still be there, as it javapcan print them correctly. Execution javapin this compiled class results in:
Compiled from "Test.java"
public class Test {
public Test();
public java.lang.String chooseRandom(java.util.List<java.lang.String>);
}
The parameterized type for java.util.List( java.lang.String) is definitely available ... I just can't figure out what it is.
I tried this:
Class clazz = [grab the type of chooseRandom parameter list first argument];
String typeName = clazz.getName();
TypeVariable[] genericTypes = clazz.getTypeParameters();
if(null != genericTypes && 0 < genericTypes.length)
{
boolean first = true;
typeName += "<";
for(TypeVariable type : genericTypes)
{
if(first) first = false;
else typeName += ",";
typeName += type.getTypeName();
}
typeName = typeName + ">";
}
It gives me typeNameof java.util.List<E>. I hope so java.util.List<java.lang.String>.
SO, , , , , ... .