注释默认“空"价值 [英] Annotation default "null" value

查看:26
本文介绍了注释默认“空"价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以指定一个默认为空的注解?

Is it possible to specify a annotation with a null as default?

我想要实现的是诸如可选注释属性之类的东西.

What I want to achieve is something like optional annotation attributes.

例如

public @interface Foo {

    Config value();

}


public @interface Config {

    boolean ignoreUnknown() default false;
    int steps() default 2;
}

我想使用@Foo(不指定值,所以它应该是某种可选的)并且我也希望能够写这样的东西:

I would like to use @Foo (without specifying the value, so it should be some kind of optional) and I would also like to be able to write something like this:

@Foo (
    @Config(
        ignoreUnknown = true,
        steps = 10
    )
)

是否可以使用注释来做这样的事情?

Is it possible to do something like this with annotations?

我不想做这样的事情

public @interface Foo {

   boolean ignoreUnknown() default false;
   int steps() default 2;
}

因为我希望能够区分属性是否已设置(而不是是否具有默认值).

because I want to be able to distinguish if a property has been set or not (and not if it has the default value or not).

描述起来有点复杂,但我正在研究一个生成 Java 代码的小注解处理器.但是在运行时,我想设置一个默认配置,该配置应该用于所有 @Foo,除了那些使用 @Config 设置自己的配置的配置.

It's a little bit complicated to describe, but I'm working on a little Annotation Processor which generates Java code. However at runtime I would like to setup a default config that should be used for all @Foo, excepted those who have set own configuration with @Config.

所以我想要的是这样的:

so what I want is something like this:

public @interface Foo {

       Config value() default null;

 }

但据我所知这是不可能的,对吧?有人知道这种可选属性的解决方法吗?

But as far as I know its not possible, right? Does anybody knows a workaround for such an optional attribute?

推荐答案

不,您不能将 null 用于注释属性值.但是,您可以使用数组类型并提供一个空数组.

No, you can't use null for an annotation attribute value. However you can use an array type and provide an empty array.

public @interface Foo {
    Config[] value();  
}
...
@Foo(value = {})

public @interface Foo {
    Config[] value() default {};  
}
...
@Foo

这篇关于注释默认“空"价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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