java 提供了一种原程序中的元素关联任何信息和元数据的途径和方法。
(1)能够读懂别人写的代码,特别是框架相关的代码(框架中使用注解是非常方便的)
(2)让编程更加简洁,代码更为清晰。
(1)源码注解:注解只有在源码中存在,编译成. class 文件就不存在了。
(2)编译时注解:注解在源码和. class 文件中都存在
(3)运行时注解:在运行阶段还起作用,甚至会影响运行逻辑的注解
(1)来自 jdk 的注解
(2)来自第三方注解
(3)我们自己定义的注解
(1)@Override 表明此方法覆盖了父类的方法(使用的最多)
(2)@Deprecated 表明此方法过时了
(3)@SuppressWarnings("deprecation") 表明忽略 deprecation 警告
代码示例
- 1 package Reflect;
- 2
- 3 abstract class Father{
- 4 public abstract String name();
- 5 public abstract int age();
- 6
- 7 @Deprecated//声明此方法过时
- 8 public abstract void sing();
- 9 }
- 10 public class Test extends Father{
- 11 @Override
- 12 public String name() {
- 13 // TODO Auto-generated method stub
- 14 return null;
- 15 }
- 16
- 17 @Override
- 18 public int age() {
- 19 // TODO Auto-generated method stub
- 20 return 0;
- 21 }
- 22
- 23 @Override//表明覆盖了父类的方法
- 24 public void sing() {
- 25 System.out.println("Father is singing...");
- 26
- 27 }
- 28 public static void main(String[] args) {
- 29
- 30 @SuppressWarnings("deprecation")//表示忽略deprecation的警告
- 31 Test t=new Test();
- 32 t.sing();
- 33
- 34 }
- 35 }
运行结果:
- Father is singing...
spring 框架、mybatis 框架和 hibernate 框架中有大量的注解
(1)@Target 指明注解的作用域
@Target({ElementType.METHOD,ElemenType.TYPE}) 红色部分表示作用域列表
作用域值 | 描述 |
CONSTRUCTOR | 构造方法声明 |
FIELD | 字段声明 |
LOCAL_VARIABLE | 局部变量声明 |
METHOD | 方法声明 |
PACKAGE | 包声明 |
PARAMETER | 参数声明 |
TYPE | 类、接口 |
(2)@Retention 指明注解的生命周期
@Retention(RetentionPolicy.RUNTIME)
来源: http://www.cnblogs.com/xiaotiaosi/p/6403306.html