java中的typeMirror,Java Annotations Processor:检查TypeMirror是否实现特定接口

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);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值