0
我有一个枚举:使用枚举作为注解
public enum Vehicle {
CAR,
BUS,
BIKE,
}
我打算用这些枚举值作为注解:@ Vehicle.CAR,@ Vehicle.BUS,@ Vehicle.BIKE。 java允许我将它们定义为注释吗?
我有一个枚举:使用枚举作为注解
public enum Vehicle {
CAR,
BUS,
BIKE,
}
我打算用这些枚举值作为注解:@ Vehicle.CAR,@ Vehicle.BUS,@ Vehicle.BIKE。 java允许我将它们定义为注释吗?
否你不能这样做。但是如果你想在注释中使用枚举,你可以这样做:
class Person {
@Presentable({
@Restriction(type = RestrictionType.LENGTH, value = 5),
@Restriction(type = RestrictionType.FRACTION_DIGIT, value = 2)
})
public String name;
}
enum RestrictionType {
NONE, LENGTH, FRACTION_DIGIT;
}
@Retention(RetentionPolicy.RUNTIME)
@interface Restriction {
//The below fixes the compile error by changing type from String to RestrictionType
RestrictionType type() default RestrictionType.NONE;
int value() default 0;
}
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.FIELD, ElementType.METHOD})
@interface Presentable {
Restriction[] value();
}
你不能使用枚举作为注释。但是你可以添加枚举作为注释的一个元素。
枚举
public enum Priority {
LOW,
MEDIUM,
HIGH
}
注释
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface TestAnnotation {
Priority priority() default Priority.MEDIUM;
}
注释使用
@TestAnnotation(priority = Priority.HIGH)
public void method() {
//Do something
}
没有,因为注释是接口,而不是价值。 –
不可以。只有注释可以用作注释。阅读教程:https://docs.oracle.com/javase/tutorial/java/annotations/index.html –
1.您的代码不会编译。 2.你的问题背后的原因是什么,这样做的好处是什么? – alfasin