java注释:元数据与代码之间的桥梁
Java注释不是代码本身,而是为程序提供元数据的辅助信息。它们为JVM和编译器提供额外的类别、接口、方法和字段数据。

注释语法:
@annotationname
public class myclass{...}
内置Java注释:
立即学习“Java免费学习笔记(深入);
Java提供了一些定义注释:
- @Override: 确保方法正确覆盖超类中的方法。如果方法名拼写错误,编译器会报错,比如“方法不会从其超类中覆盖”。
class Parent {
void display(){
System.out.println("hello from parent class");
}
}
class Child extends Parent{
@Override
void display(){
System.out.println("hello from child class");
}
}
- @Deprecated: 建议避免在后续版本中使用标记方法或类别过时。
class Sum {
@Deprecated
int calcSum(int a, int b){
return a+b;
}
}
- @SuppressWarnings: 抑制编译器警告。 帮助保持代码清洁。
@SuppressWarnings("deprecation")
public class Main {
public static void main(String[] args) {
Sum sum = new Sum();
int sumValue = sum.calcSum(1,2);
System.out.println("sum is=" + sumValue);
}
}
元注释(自定义注释):
Java还为描述自定义注释提供了一些元注释:
- @Target: 哪些程序元素(类别、方法、字段等)可以应用于指定注释。). @Target(ElementType.TYPE) 表示只能应用于类别。
- @Retention: 指定注释可以在哪个阶段使用(源代码、编译和操作)。
- @Inherited: 指定注释是否可以由子类继承。
- @Documented: 生成的Javadoc文件中是否应包含指定注释。
注释类型:
- 标记注释: 没有任何成员的注释。 例如:@Override, @Deprecated。 @interface MyAnnotation {}
- 单值注释: 只有一个成员的注释。
@interface MyAnnotation {
int num();
}
// 应用
@MyAnnotation(num=1)
- 多值注释: 多个成员的注释。
@interface MyAnnotation {
int num1();
int num2();
}
// 应用
@MyAnnotation(num1=1, num2=2)
创建自定义注释:
使用@interface关键字定义自定义注释:
@Retention(RetentionPolicy.RUNTIME) // 可在运行过程中访问
@Target(ElementType.METHOD) // 只能应用于方法
@interface Review {
String reviewerName() default "unknown";
}
应用自定义注释:
public class CodeReview {
@Review(reviewerName = "John")
public void reviewmethod1() {
System.out.println("I need review");
}
@Review(reviewerName = "Mike")
public void reviewmethod2() {
System.out.println("I also need review");
}
}
读取自定义注释(Java反射):
public class MainExample {
public static void main(String[] args) {
Class<CodeReview> obj = CodeReview.class;
for(Method method : obj.getDeclaredMethods()){
if(method.isAnnotationPresent(Review.class)){
Review annotation = method.getAnnotation(Review.class);
System.out.println("Method: " + method.getName() + "| Reviewer: " + annotation.reviewerName());
}
}
}
}
输出:
Method: reviewmethod1 | Reviewer: John Method: reviewmethod2 | Reviewer: Mike
在运行过程中,通过Java反射API可以访问和处理注释信息。 希望本教程能帮助您更好地理解Java注释。 如有疑问,请随时提出。
以上是Java注释的详细内容,请关注图灵教育的其他相关文章!