java 获取类注释,Java 6注释处理 - 从注释中获取类

I have an custom annotation called @Pojo which I use for automatic wiki documentation generation:

package com.example.annotations;

import java.lang.annotation.ElementType;

import java.lang.annotation.Retention;

import java.lang.annotation.RetentionPolicy;

import java.lang.annotation.Target;

@Retention(RetentionPolicy.SOURCE)

@Target(ElementType.METHOD)

public @interface Pojo {

Class> value();

}

I use it like this:

@Pojo(com.example.restserver.model.appointment.Appointment.class)

to annotation a resource method so that the annotation processor can automatically generate a wiki page describing the resource and type that it expects.

I need to read the value of the value field in an annotation processor, but I am getting a runtime error.

In the source code for my processor I have the following lines:

final Pojo pojo = element.getAnnotation(Pojo.class);

// ...

final Class> pojoJavaClass = pojo.value();

but the actual class in not available to the processor. I think I need a javax.lang.model.type.TypeMirror instead as a surrogate for the real class. I'm not sure how to get one.

The error I am getting is:

javax.lang.model.type.MirroredTypeException: Attempt to access Class object for TypeMirror com.example.restserver.model.appointment.Appointment

The Appointment is a class mentioned in one of my @Pojo annotation.

Unfortunately, document and/or tutorials on Java annotation processing seems scarce. Tried googling.

解决方案

There the trick is to actually use getAnnotation() and catch the MirroredTypeException. Surprisingly the exception then provides the TypeMirror of the required class.

I don't know if this is a good solution, but it is one. In my personal opinion I would try to get the type behind the MirroredType, but I don't know if this is possible.

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值