Java Annotations Processor: Check if TypeMirror implements specific interface

你离开我真会死。 提交于 2019-12-04 18:12:17

问题


I'm working with on a Java annotations processor. My annotation, @foo is used to mark field variables that can be read to a file or from a file during runtime. However, I would like to check if the variable type implements Serializable during compile time, so that if the field is not serializable I can give a warning/error at compile time.

(I don't need to actually check if the object IS serializable, if it implements the Serializable interface I'll trust it).

I have figured out how to do the other stuff, but I can't figure out how to check if the element implements Serializable. I can use the TypeElement#getInterfaces method, but I can't figure out how to check if any of these TypeMirror's returned are the one for Serializable.

Also, if anybody happens to know any good java.lang.model or Java Annotations tutorials, that would be helpful as well.

Edit: I have tried this...

isSerializable = false  
for(TypeMirror tm : processingEnv.getTypeUtils().directSupertypes(em.asType()))  
{  
if(isSerializable = "java.io.Serializable".equals(tm.toString()))  
{  
break;  
}  
}  

It works alright for String and Character, which directly implement Serializable, but for Integer, which inherits Serializable from the Number superclass, it does not work.


回答1:


Instead of checking the direct supertypes, you should use Types.isAssignable to check if Serializable is one of the supertypes of the TypeMirror:

TypeMirror serializable = elementUtil.getTypeElement("java.io.Serializable").asType();
boolean isSerializable = typeUtil.isAssignable(tm, serializable);


来源:https://stackoverflow.com/questions/20358039/java-annotations-processor-check-if-typemirror-implements-specific-interface

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!