[英]Java Annotations Processor: Check if TypeMirror implements specific interface
I'm working with on a Java annotations processor. 我正在使用Java注释处理器。 My annotation, @foo
is used to mark field variables that can be read to a file or from a file during runtime. 我的注释, @foo
用于标记可在运行时读取到文件或文件的字段变量。 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. 但是,我想检查变量类型是否在编译期间实现Serializable
,这样如果该字段不可序列化,我可以在编译时给出警告/错误。
(I don't need to actually check if the object IS serializable, if it implements the Serializable
interface I'll trust it). (我不需要实际检查对象是否可序列化,如果它实现了Serializable
接口我会信任它)。
I have figured out how to do the other stuff, but I can't figure out how to check if the element implements Serializable
. 我已经想出了如何做其他的东西,但我无法弄清楚如何检查该元素是否实现了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
. 我可以使用TypeElement#getInterfaces
方法,但我无法弄清楚如何检查返回的任何TypeMirror
是否是Serializable
。
Also, if anybody happens to know any good java.lang.model
or Java Annotations tutorials, that would be helpful as well. 此外,如果有人碰巧知道任何好的java.lang.model
或Java Annotations教程,那么这也会有所帮助。
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. 它适用于直接实现Serializable
String和Character,但对于从Number超类继承Serializable的Integer,它不起作用。
Instead of checking the direct supertypes, you should use Types.isAssignable
to check if Serializable
is one of the supertypes of the TypeMirror
: 而不是检查直接超的,你应该使用Types.isAssignable
检查Serializable
是的超类型之一 TypeMirror
:
TypeMirror serializable = elementUtil.getTypeElement("java.io.Serializable").asType();
boolean isSerializable = typeUtil.isAssignable(tm, serializable);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.