getting qualified type names of parameters (and defined classes) from pmd's java ast

Viewed 15

i need to get the qualified name of classes and method parameters in order to build a consistent way of addressing methods across different libraries.

for the sake of illustration, a very artificial method declared as

public class VariousArgumentTypes {
  class InnerType {
  }

  int mixedArguments(int i, int[] is, String s, InnerType[] its) {
    return i;
  }
}

should compute to a signature VariousArgumentTypes.mixedArguments(int, int[], java.lang.String, VariousArgumentTypes$InnerType[])

while trying to get the types of the parameters, according to the documentation on formal parameters i should be able to use getType() with a caveat that it may return null. i don't know what may means specifically but so far for me, it has always returned null.

ASTFormalParameters params = methodDeclaration.getFormalParameters();
for (ASTFormalParameter param : params) {
  System.out.println(param.getType());
}

prints null for every source code parameter type i've tried, which includes all primitives, arrays, varargs, java.lang objects like String, objects needing imports like Set and custom classes declared as subclasses of the one i'm building the ast for. so calling getName() of course throws a NullPointerException. the same behaviour also occurs when using param.getVariableDeclaratorId().getType() as well as param.getVariableDeclaratorId().getNameDeclaration(), param.getTypeDefinition() and param.getTypeNode().getType() .

the closest i could get was through param.getTypeNode().getTypeImage() which however isn't specific enough for my needs.

similarly, for classes (accessed as variables of type ASTAnyTypeDeclaration) the documentation states i should use getBinaryName(). but this also triggers NullPointerExceptions on every source class i tried.

i'm running this from a maven project with the following pmd dependency:

<dependency>
  <groupId>net.sourceforge.pmd</groupId>
  <artifactId>pmd-java</artifactId>
  <version>6.49.0</version>
</dependency>
0 Answers
Related