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

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

问题描述

java 中的@interface 注解.

@interface Annotation in java.

如果我添加@Target(value=ElementType.METHOD),这个注解可以被导入Java Method.

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)

一旦我添加了customer Annotation,它会自动检查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 Reflect in Runtime检查的想法,这不符合我的想法.

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由JDK的javax.annotation.processingjavax.lang.model包提供,编译时会调用,并制作必要的检查.(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) 例如,给定注解

(1) For example, given the annotation

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/services/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

当您编译代码时,将调用注释处理器.要使用它,命令行应该是这样的:

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天全站免登陆