登录
首页 >  文章 >  java教程

Java的注释

时间:2025-02-19 15:52:18 337浏览 收藏

你在学习文章相关的知识吗?本文《Java的注释》,主要介绍的内容就涉及到,如果你想提升自己的开发能力,就不要错过这篇文章,大家要知道编程理论基础和实战操作都是不可或缺的哦!

Java注释:元数据与代码的桥梁

Java注释并非代码本身,而是为程序提供元数据的辅助信息。它们为JVM和编译器提供关于类、接口、方法和字段的附加数据。

Java的注释

注释语法:

@annotationname
public class myclass{...}

内置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 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的注释》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

相关阅读
更多>
最新阅读
更多>
课程推荐
更多>