Dan*_*ski 219 java annotations
今天我想按照这个文档创建我的第一个注释界面,我得到了编译器错误
Run Code Online (Sandbox Code Playgroud)Invalid type for annotation member": public @interface MyAnnotation { Object myParameter; ^^^^^^ }
显然Object不能用作注释成员的类型.不幸的是,我找不到任何关于哪些类型可以使用的信息.
我发现这是使用反复试验:
String →有效int →有效Integer →无效(令人惊讶)String[] →有效(令人惊讶)Object →无效也许某人可以了解实际允许哪些类型以及原因.
ska*_*man 299
它由JLS的第9.6.1节规定.注释成员类型必须是以下之一:
它似乎有限制,但毫无疑问有理由.
另请注意,String[][]上述规则隐式禁止多维数组(例如).
KLE*_*KLE 58
我同意Skaffman的可用类型.
附加限制:它必须是编译时常量.
例如,禁止以下内容:
@MyAnnot("a" + myConstantStringMethod())
@MyAnnot(1 + myConstantIntMethod())
Run Code Online (Sandbox Code Playgroud)
fik*_*nik 26
另外,不要忘记注释本身可以是注释定义的一部分.这允许一些简单的注释嵌套 - 在您希望多次出现一个注释的情况下很方便.
例如:
@ComplexAnnotation({
@SimpleAnnotation(a="...", b=3),
@SimpleAnnotation(a="...", b=3),
@SimpleAnnotation(a="...", b=3)
})
public Object foo() {...}
Run Code Online (Sandbox Code Playgroud)
这里SimpleAnnotation是
@Target(ElementType.METHOD)
public @interface SimpleAnnotation {
public String a();
public int b();
)
Run Code Online (Sandbox Code Playgroud)
并且ComplexAnnotation是
@Target(ElementType.METHOD)
public @interface ComplexAnnotation {
public SimpleAnnotation[] value() default {};
)
Run Code Online (Sandbox Code Playgroud)
示例来自:https://blogs.oracle.com/toddfast/entry/creating_nested_complex_java_annotations
小智 11
注释的概念非常适合我的项目设计,直到我意识到注释中不能有复杂的数据类型.我通过使用我想要实例化的类而不是该类的实例化对象来解决它.它并不完美,但java很少.
@interface Decorated { Class<? extends PropertyDecorator> decorator() }
interface PropertyDecorator { String decorate(String value) }
class TitleCaseDecorator implements PropertyDecorator {
String decorate(String value)
}
class Person {
@Decorated(decorator = TitleCaseDecorator.class)
String name
}
Run Code Online (Sandbox Code Playgroud)