java注释:元数据与代码的桥梁
Java注释并非代码本身,而是为程序提供元数据的辅助信息。它们为JVM和编译器提供关于类、接口、方法和字段的附加数据。
注释语法:
@annotationname public class myclass{...}
内置Java注释:
立即学习“Java免费学习笔记(深入)”;
Java提供了一些预定义的注释:
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"); } }
class Sum { @Deprecated int calcSum(int a, int b){ return a+b; } }
@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还提供了一些元注释,用于描述自定义注释:
注释类型:
@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的注释的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号