简体   繁体   English

如何在Java注释中返回对象?

[英]How to return an object in a Java annotation?

I am making a Test annotation, and I want to be able for the user to specify an expected return value. 我正在制作测试注释,我希望能够让用户指定预期的返回值。

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Test {
    Object value() default null;
    Class<? extends Throwable> exception() default NoException.class;
    int timeout() default 0;
}

As I know, you cannot specify Object as the return type in annotation methods. 据我所知,您不能将Object指定为注释方法中的返回类型。

I am wondering if there is a return type which allows primitives AND strings to be returned. 我想知道是否存在允许返回基元和字符串的返回类型。

If not, is it possible to create? 如果没有,是否可以创建? Thank you. 谢谢。

In short no. 总之没有。 The oracle docs explain this oracle文档解释了这一点

Return types are restricted to primitives, String, Class, enums, annotations, and arrays of the preceding types. 返回类型仅限于基元,字符串,类,枚举,注释和前面类型的数组。 Methods can have default values 方法可以具有默认值

See here for the Oracle documents on this. 请参阅此处以获取有关此文档的Oracle文档。

If you could pass an object what would be the syntax? 如果你可以传递一个对象,那么语法是什么? The items that are passed have to be constants which is why there is the restriction 传递的项必须是常量,这就是限制的原因

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM