Javaparser: get generic class of a method return type like List<MyClass>

1.1k Views Asked by At

I'm processing a Java source file using the java-parser library.

I have this situation in the analyzed source code:

 List<Allergen> getList() {
        return EnumSet.allOf(Allergen.class).stream()
                .filter(this::isAllergicTo)
                .collect(Collectors.toList());
    }

I need to access the generic class of the List return type ( Allergen in this example)

I'm using an extension of VoidVisitorAdapter class in my analyzer

Here an extract of the code:

public class PlaceholderNormalizer extends VoidVisitorAdapter<String> {

 ...
 ...
 
 
 @Override
    public void visit(MethodDeclaration n, String arg) {
        logger.debug("MethodDeclaration: {}", n.getName().asString());
        logger.debug(" --- " + n.getTypeAsString());  // prints: List<Allergen>
    
    // DO SOME STUFF
        super.visit(n, arg);
    }
  
  ...
  ...
}

I can obtain a Type object of the node MethodDeclaration using n.getType()

But, I don't understand how to retrieve the Allergen class.

Please I need some help

1

There are 1 best solutions below

0
Michał Krzywański On BEST ANSWER

In case of this method the n.getType will return instance of ClassOrInterfaceType. To get to generic parameter you can obtain it as this type and use ClassOrInterfaceType::getTypeArguments method :

@Override
public void visit(MethodDeclaration n, String arg) {
    Type type = n.getType();

    if(type instanceof ClassOrInterfaceType) {
        ClassOrInterfaceType classOrInterfaceType = type.asClassOrInterfaceType();
        Optional<NodeList<Type>> typeArguments = classOrInterfaceType.getTypeArguments();

        //list of arguments might have different length
        typeArguments.ifPresent(types -> System.out.println(types.get(0)));
    }
        // DO SOME STUFF
     super.visit(n, arg);
}

This will print Allergen.