Reputation: 4798
I am using javaparser to parse and analyse some classes and to generate an adequate response. I have a problem detecting if a method's argument is an enum.
A class is parsed and list of methods is fetched. When I iterate through this list I also fetch arguments of these methods. Then I have a problem finding out which of these are enums. For instance:
...
Collection<MethodDeclaration> methods = parsed.getMethods();
int numberOfEnums = methods.stream().map(parameter -> {
if(<detect here if parameter is an enum>) {
return 1;
}
return 0;
}).reduce(0, (a, b) -> a + b);
Parameter in the stream is of type com.github.javaparser.ast.body.Parameter
.
This is just a simple example of an usage (reporting on how many enums are in the method arguments). However, I need it for something much more complex.
Analyzed source is a java code file, which means, in a general case, we cannot assume a parameter class is reachable in the current VM's class-path.
Upvotes: 0
Views: 124
Reputation: 382
It's a little complicated but totally doable. First you need to resolve the parameters to know their type. Then you can access the type declaration which lets you know if it is an enumeration.
Below is a code snippet that allows you to do this.
ResolvedType rt = param.resolve().getType();
boolean isEnum = rt.isReferenceType() ? rt.asReferenceType().getTypeDeclaration().map(td -> td.isEnum()).orElse(false): false;
Upvotes: 2