bill geo bill geo - 23 days ago 8
Java Question

How to extract the single type of a parameterized type using jdt

I am trying to parse some java source files and get some info using AST. Currently I want to somehow get the type of parameterized types eg from

List<String>
I need the
String
.

public boolean visit(VariableDeclarationFragment f) {
if (f.getParent() instanceof FieldDeclaration) {
FieldDeclaration d = (FieldDeclaration) f.getParent();
if (d.getType().isParameterizedType()) {
System.out.println("Par type : " + d.getType().toString());
}
}
}


This snippet gives me the
List<String>
.
Any ideas on how to proceed?

Answer

You need to cast the Type to ParametrizedType and extract the inner type.

public boolean visit(VariableDeclarationFragment f) {
  if (f.getParent() instanceof FieldDeclaration) {
    FieldDeclaration d = (FieldDeclaration) f.getParent();
    if (d.getType().isParameterizedType()) {
      ParameterizedType parType = (ParameterizedType) d.getType();
      System.out.println("Par type : " + parType.typeArguments().get(0).toString());
    }
  }
}
Comments