java注解
来源:互联网 发布:添加网络歌曲到空间 编辑:程序博客网 时间:2024/06/05 17:01
一、java 自身的注解
- @Deprecated 表明当前的元素已经不推荐使用
- @Override 表明当前方法是覆盖了父类方法
- @SuppressWarnings 关闭编译器警告信息
二、自定义注解
接口声明
1 @Target(ElementType.METHOD)2 @Retention(RetentionPolicy.RUNTIME)3 public @interface MyMethodAnnotation {4 5 }
使用自定义注解
1 public class AnnotationDemo { 2 3 @MyMethodAnnotation 4 public void test() { 5 6 } 7 8 @MyMethodAnnotation 9 public void test2() {10 11 }12 13 public void test3() {14 15 }16 }
测试
1 public class Client { 2 3 public static void main(String[] args) { 4 Method[] methods = AnnotationDemo.class.getMethods(); 5 for(Method m : methods) { 6 if(m.isAnnotationPresent(MyMethodAnnotation.class)) { 7 System.out.println("----- " + m.getName() + " -------"); 8 } 9 }10 }11 }
结果
----- test ------------ test2 -------
三、元注解
作用负责注解其它注解
@Target
@Retention
@Documented
@Inherited
1、@Target : 描述注解的使用范围
取值(ElementType)有,
public enum ElementType { /** Class, interface (including annotation type), or enum declaration */ TYPE, // 用于描述类、接口(包括注解类型) 或enum声明 /** Field declaration (includes enum constants) */ FIELD, // 用于描述域 /** Method declaration */ METHOD, // 用于描述方法 /** Parameter declaration */ PARAMETER, // 用于描述参数 /** Constructor declaration */ CONSTRUCTOR, // 用于描述构造函数 /** Local variable declaration */ LOCAL_VARIABLE, // 用于描述局部变量 /** Annotation type declaration */ ANNOTATION_TYPE, /** Package declaration */ PACKAGE // 用于描述包}
2、@Retention : 描述注解的生命周期
public enum RetentionPolicy { /** * Annotations are to be discarded by the compiler. */ SOURCE, //在源文件有效 保留在源文件 /** * Annotations are to be recorded in the class file by the compiler * but need not be retained by the VM at run time. This is the default * behavior. */ CLASS, //在class文件有效 保留在class文件 /** * Annotations are to be recorded in the class file by the compiler and * retained by the VM at run time, so they may be read reflectively. * * @see java.lang.reflect.AnnotatedElement */ RUNTIME //在运行时有效 运行时保留}
3、@Documented : 用于描述其它类型的annotation应该被作为被标注的程序成员的公共API,因此可以被例如javadoc此类的工具文档化
4、@Inherited :阐述了某个被标注的类型是被继承的。如果一个使用了@Inherited修饰的annotation类型被用于一个class,则这个annotation将被用于该class的子类。
四、启示
想想,自定义注解还是有很多好处的。junit测试框架,方法上注解@Test,@Before, @After。没看过它的底层实现,不过仔细想想,无非也是通过运行期反射去拿到定义在方法的注解,
根据不同注解类型,来执行不同的操作。
0 0
- Java注解-自定义注解
- Java注解----自定义注解
- Java注解自定义注解
- Java注解--四种元注解
- Java注解-三种內建注解
- 【Java】【注解】自定义注解
- java注解
- java注解
- java注解
- java 注解
- Java注解
- java 注解
- Java 注解
- Java注解
- java 注解
- JAVA注解
- Java注解
- Java注解
- 模板模式讲解二
- mac svn的替代品CornerStone
- mac下8080端口到80端口的转发
- ConstraintLayout
- Mac窗口管理管理软件SizeUp
- java注解
- chrome插件
- spring jdbcTemplate源码剖析
- 求最大公约数最小公倍数
- 搭建maven+spring+mybatis工程
- Spring ProxyFactory
- Spring ApplicationContextAware获取上下文
- operator重写
- 第三十一、Java面向对象三大特征之多态