Java Annotations Processor:检查TypeMirror是否实现特定接口 [英] Java Annotations Processor: Check if TypeMirror implements specific interface
问题描述
我正在使用Java注释处理器。我的注释 @foo
用于标记可在运行时读取到文件或文件的字段变量。但是,我想检查变量类型是否在编译期间实现 Serializable
,这样如果该字段不可序列化,我可以在编译时发出警告/错误。 / p>
(我不需要实际检查对象是否可序列化,如果它实现了 Serializable
接口我'我会相信它。)
我已经想出了如何做其他的事情,但我无法弄清楚如何检查该元素是否实现序列化
。我可以使用 TypeElement#getInterfaces
方法,但我无法弄清楚如何检查这些 TypeMirror
返回的是 Serializable
。
此外,如果有人碰巧知道任何好的 java.lang.model
或Java Annotations教程,也会有所帮助。
编辑:我试过这个......
isSerializable = false
for(TypeMirror tm:processingEnv.getTypeUtils()。directSupertypes(em.asType()) )
{
if(isSerializable =java.io.Serializable.equals(tm.toString()))
{
break;
}
}
它适用于String和Character,它直接实现 Serializable
,但是对于从Number超类继承Serializable的Integer,它不起作用。
您应该使用 Types.isAssignable
检查 Serializable
是否一个 TypeMirror
的超类型:
TypeMirror serializable = elementUtil.getTypeElement(java.io.Serializable)。asType();
boolean isSerializable = typeUtil.isAssignable(tm,serializable);
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.
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);
这篇关于Java Annotations Processor:检查TypeMirror是否实现特定接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!