Java 6注释处理 - 从注释中获取类 [英] Java 6 annotation processing -- getting a class from an annotation

查看:1020
本文介绍了Java 6注释处理 - 从注释中获取类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为@Pojo的自定义注释,我用它来生成自动维基文档:

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

我这样使用它:

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

注释资源方法,以便注释处理器可以自动生成一个wiki页面,描述它所期望的资源和类型。

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

但实际的类不适用于处理器。我想我需要一个 javax.lang.model.type.TypeMirror 作为真实类的代理。我不确定如何获得一个。

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.

我得到的错误是:

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

约会是我的一个 @Pojo 注释。

不幸的是,关于Java注释处理的文档和/或教程似乎很少。尝试谷歌搜索。

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

推荐答案

你读过这篇文章: http://blog.retep.org/2009/02/13/getting-class-values- from-annotations-in-annotationprocessor /


诀窍是实际使用getAnnotation()并捕获MirroredTypeException。令人惊讶的是,异常然后提供了所需类的TypeMirror。

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

我不知道这是否是一个好的解决方案,但它是一。在我个人看来,我会尝试获得MirroredType背后的类型,但我不知道这是否可行。

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.

这篇关于Java 6注释处理 - 从注释中获取类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆