有没有什么办法让这个批注自动检查Java方法参数类型 [英] Is there any way to let this annotation auto-check the Java Method arguments type

查看:278
本文介绍了有没有什么办法让这个批注自动检查Java方法参数类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

@interface注释在java中。

@interface Annotation in java.

如果我添加@Target(值= ElementType.METHOD),这个注解可以用于进口Java方法。

If I add @Target(value=ElementType.METHOD),this annotation can be import for Java Method.

有没有什么办法让这个批注自动检查Java方法参数类型?

Is there any way to let this annotation auto-check the Java Method arguments type?

喜欢的东西,我有一个方法:

Something like, I have a method:

    @Annotation(type=Integer)
    sayHello(String name)

在我添加了客户注释,它会自动检查sayHello的参数类型是匹配与否,如果它不匹配,会导致编译错误。

Once I add the customer Annotation, it will auto check the sayHello argument type is match or not,if it is not match,it will cause the compile error.

时可以实现?如果,怎么样?使用Java反映在运行时检查排除想,这将不适合我的想法。

Is it can be implemented? If, how? Exclude the thought using java Reflect in Runtime to check,this will not fit my idea.

先谢谢了。

推荐答案

您需要
(1)使自己的注解处理器,其API是由 javax.annotation.processing中 javax.lang.model 提供JDK的软件包可以在编译过程中被调用,并进行必要的检查。
(2)使用SPI连接它

You need to (1) make your own annotation processor whose API is provided by javax.annotation.processing and javax.lang.model packages of JDK which will be invoked during compilation and make necessary checks. (2) attach it using SPI

(1)例如,给定注解

package aptest;    
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Retention(RetentionPolicy.SOURCE)
public @interface Annotation {
    Class<?> type();
}

注解处理器可能是这样的:

the annotation processor might look like this:

package aptest;
// ... imports
@SupportedAnnotationTypes({"aptest.Annotation"})
public class AnnotationProcessor extends AbstractProcessor 
    implements Processor {

    @Override
    public boolean process(Set<? extends TypeElement> annotations,
            RoundEnvironment roundEnv) {        
        for (TypeElement te : annotations) {
              for (Element e : roundEnv.getElementsAnnotatedWith(te)) {
                  // do your checking
              }
        }
        return true;
    }

}

(2)当您打包注解处理器(让我们在aptest.jar说)你包括含有 META-INF /服务/ javax.annotation.processing.Processor ​​文件你注解处理器类的名称:

(2) When you package your annotation processor (let's say in aptest.jar) you include META-INF/services/javax.annotation.processing.Processor file containing the name of you annotation processor class:

aptest.AnnotationProcessor

当您编译code注解处理器将被调用。要使用它,在命令行想是这样的:

And when you compile your code the annotation processor will be invoked. To use it, the command line should like like this:

javac -cp aptest.jar SayHello.java

这篇关于有没有什么办法让这个批注自动检查Java方法参数类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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