Mic*_*Sim 16 java language-features annotations interface
在使用注释时,我偶然发现了以下代码(这是Hibernate @NotNull注释):
@Target(value = {ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER})
@Retention(value = RetentionPolicy.RUNTIME)
@Documented
@Constraint(validatedBy = {})
public @interface NotNull {
@Target(value = {ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER})
@Retention(value = RetentionPolicy.RUNTIME)
@Documented
public @interface List {
public NotNull[] value();
}
public String message() default "{javax.validation.constraints.NotNull.message}";
public Class<?>[] groups() default {};
public Class<? extends Payload>[] payload() default {};
}
Run Code Online (Sandbox Code Playgroud)
我想知道default方法定义中的关键字/构造,这是我以前从未见过的.据我所知,它允许您为此方法(或注释属性)定义默认值.
现在我试图将此构造应用于普通接口,但它失败了.这将无法编译:
public interface DefaultTest {
public String test() default "value";
}
Run Code Online (Sandbox Code Playgroud)
但这会奏效:
public @interface DefaultTest {
public String test() default "value";
}
Run Code Online (Sandbox Code Playgroud)
所以我的问题是:关键字注释是否default特定?如果是,那么在正常的接口定义中反对使用这个结构有什么用呢?
Pac*_*ace 22
Java 8及以后版本
是的,现在可以在接口上使用default关键字.有关更多详细信息,请参阅Oracle的文档.
实施与您的想法略有不同.这将是:
public interface DefaultTest {
default public String test() {
return "value";
}
}
Run Code Online (Sandbox Code Playgroud)
Java 7和之前的版本
default关键字只能用于注释.
如果需要接口的默认返回值,则需要使用抽象类.
public abstract class DefaultTest {
public String test() {
return "value";
}
}
Run Code Online (Sandbox Code Playgroud)
小智 6
此处的'default'关键字不特定于注释。Java的功能是提供接口方法的默认实现。
需要此行为: 假设最初定义了“车辆”接口以支持所有车辆功能方法-
interface Vehicle {
void speed();
...
//other interface methods
}
Run Code Online (Sandbox Code Playgroud)
现在,实现此Vehicle接口的类已经实现了这些抽象方法。
现在将来,车辆具有飞行能力。因此,您还需要添加飞行功能。现在,如果将flyingSpeed()方法添加到Vehicle接口,则需要修改所有现有的类,以免破坏代码。不可行的解决方案。
为了向后兼容,java提供了Default方法的功能。这样您就可以添加新方法来与默认实现接口,因此现有类无需实现该方法。并且新的Vehicle类可以根据需要覆盖这些方法。
interface Vehicle {
void speed();
...
//other interface methods
//default method
default void flyingSpeed() {
System.out.println("Default flying speed");
}
}
Run Code Online (Sandbox Code Playgroud)
使用这种方法,以前的Vehicle类可以不需要实现此方法。
有关更多信息,请参见此处。
| 归档时间: |
|
| 查看次数: |
19940 次 |
| 最近记录: |