I have annotation parser, inside it i use this piece of code:
Set<? extends Element> annotatedElements = roundEnv.getElementsAnnotatedWith(annotation);
for (Element el : annotatedElements) {
try {
TypeElement targetClass = (TypeElement) el;
List<? extends VariableElement> fields = getFields(targetClass);
for (VariableElement e : fields) {
String type = getType(e);
String name = getVariableName(e));
}
} catch (IOException e) {
e.printStackTrace();
}
}
And methods:
public List<? extends VariableElement> getFields(TypeElement targetClass) {
List<? extends Element> enclosedElements = targetClass.getEnclosedElements();
List<VariableElement> fields = new ArrayList<>(enclosedElements.size());
for (Element field : enclosedElements) {
if (field.getKind() == ElementKind.FIELD && !field.getModifiers().contains(Modifier.STATIC)) {
fields.add((VariableElement) field);
}
}
return fields;
}
public String getType(VariableElement variable) {
if (variable instanceof PrimitiveType) {
return variable.asType().toString();
}
return ((DeclaredType) variable.asType()).asElement().toString();
}
The first methods gets all non static fields inside the class.
And the second method should get type of the variable as String, so "String", "boolean", "MyObject" and so on. However when the field is type of boolean i get this error:
com.sun.tools.javac.code.Type$JCPrimitiveType cannot be cast to javax.lang.model.type.DeclaredType
I expected boolean and other primitive types to be type of PrimitiveType however for some reason it is com.sun.tools.javac.code.Type$JCPrimitiveType
Same, when i try to get all getters from the class:
public List<? extends VariableElement> getGetterMethods(TypeElement targetClass) {
List<? extends Element> enclosedElements = targetClass.getEnclosedElements();
List<VariableElement> fields = new ArrayList<>(enclosedElements.size());
for (Element field : enclosedElements) {
if (field.getKind() == ElementKind.METHOD &&
!field.getModifiers().contains(Modifier.STATIC) &&
(field.getSimpleName().toString().startsWith("get") || field.getSimpleName().toString().startsWith("is"))) {
fields.add((VariableElement) field);
}
}
return fields;
}
I get error:
java.lang.ClassCastException: com.sun.tools.javac.code.Symbol$MethodSymbol cannot be cast to javax.lang.model.element.VariableElement
It seems com.sun.tools.javac.code package should be part of the JDK however I cannot find it anyhwere. And thus i cannot import it and maybe make some adjustments.
WHat is the best way to deal with this error? Even if i could import the package, it seems the types of it are weirdly assigned, as i would expect types of it to be part of javax.lang.model.element package.
Thanks for help!
//edit
according to docs :
public static class Type.JCPrimitiveType
extends Type
implements PrimitiveType
so the Type.JCPrimitiveType should be instanceOf PrimitiveType, yet the if does not hold true when executing for some reason