自从90年代末在大学期间使用JBuilder以来我没有触及Java,所以我有点失去联系 - 无论如何我本周一直在研究一个小型Java项目,并使用Intellij IDEA作为我的IDE ,改变我的常规.Net开发速度。
我注意到它支持添加接口和@interfaces,什么是@interface,它与普通接口有什么不同?
public interface Test {
}
与
public @interface Test {
}
我做了一些搜索,但找不到大量有用的信息引用@interface。
接口:
通常,接口公开合同而不暴露底层实现细节。在面向对象编程中,接口定义了暴露行为但不包含逻辑的抽象类型。实现由实现接口的类或类型定义。
@interface :(注释类型)
以下面的例子,其中有很多评论:
public class Generation3List extends Generation2List {
// Author: John Doe
// Date: 3/17/2002
// Current revision: 6
// Last modified: 4/12/2004
// By: Jane Doe
// Reviewers: Alice, Bill, Cindy
// class code goes here
}
您可以声明注释类型,而不是这样
@interface ClassPreamble {
String author();
String date();
int currentRevision() default 1;
String lastModified() default "N/A";
String lastModifiedBy() default "N/A";
// Note use of array
String[] reviewers();
}
然后可以按如下方式对类进行注释:
@ClassPreamble (
author = "John Doe",
date = "3/17/2002",
currentRevision = 6,
lastModified = "4/12/2004",
lastModifiedBy = "Jane Doe",
// Note array notation
reviewers = {"Alice", "Bob", "Cindy"}
)
public class Generation3List extends Generation2List {
// class code goes here
}
PS:许多注释取代了代码中的注释。
参考:http://docs.oracle.com/javase/tutorial/java/annotations/declaring.html
interface
关键字表示您在Java中声明传统的接口类。
@interface
关键字用于声明新的注释类型。
有关语法的说明,请参阅注释中的docs.oracle tutorial。
如果你真的想了解JLS的含义细节,请参阅@interface
。
interface:
定义了实现它的类的合同
@interface:
定义了注释的合同
Java编程语言中的接口是一种抽象类型,用于指定类必须实现的行为。它们与协议类似。接口使用interface关键字声明
@interface用于创建自己的(自定义)Java注释。注释在它们自己的文件中定义,就像Java类或接口一样。这是自定义Java注释示例:
@interface MyAnnotation {
String value();
String name();
int age();
String[] newNames();
}
此示例定义了一个名为MyAnnotation的注释,它有四个元素。注意@interface关键字。这向Java编译器发出信号,表明这是Java注释定义。
请注意,每个元素的定义与接口中的方法定义类似。它有一个数据类型和名称。您可以将所有原始数据类型用作元素数据类型。您还可以使用数组作为数据类型。您不能将复杂对象用作数据类型。
要使用上面的注释,您可以使用以下代码:
@MyAnnotation(
value="123",
name="Jakob",
age=37,
newNames={"Jenkov", "Peterson"}
)
public class MyClass {
}