Java注解入门
2016-01-15 23:32
609 查看
注解的分类
按运行机制分:
源码注解:只在源码中存在,编译后不存在
编译时注解:源码和编译后的class文件都存在(如@Override,@Deprecated,@SuppressWarnings)
运行时注解:能在程序运行时起作用(如spring的依赖注入)
按来源分:
来自JDK的注解
第三方的注解
自定义的注解
自定义注解
如下实例给出了自定义注解的基本方法
使用注解
解析java注解
按运行机制分:
源码注解:只在源码中存在,编译后不存在
编译时注解:源码和编译后的class文件都存在(如@Override,@Deprecated,@SuppressWarnings)
运行时注解:能在程序运行时起作用(如spring的依赖注入)
按来源分:
来自JDK的注解
第三方的注解
自定义的注解
自定义注解
如下实例给出了自定义注解的基本方法
package com.flypie.annotations; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /* @Target,@Retention,@Inherited,@Documented * 这四个是对注解进行注解的元注解,负责自定义的注解的属性 */ @Target({ElementType.TYPE,ElementType.METHOD}) //表示注解的作用对象,ElementType.TYPE表示类,ElementType.METHOD表示方法 @Retention(RetentionPolicy.RUNTIME) //表示注解的保留机制,RetentionPolicy.RUNTIME表示运行时注解 @Inherited //表示该注解可继承 @Documented //表示该注解可生成文档 public @interface Design { String author(); //注解成员,如果注解只有一个成员,则成员名必须为value(),成员类型只能为原始类型 int data() default 0; //注解成员,默认值为0 }
使用注解
package com.flypie; import com.flypie.annotations.Design; @Design(author="flypie",data=100) //使用自定义注解,有默认值的成员可以不用赋值,其余成员都要复值 public class Person { @Design(author="flypie",data=90) public void live(){ } }
解析java注解
package com.flypie; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import com.flypie.annotations.Design; public class Main { public static void main(String[] args) throws ClassNotFoundException { Class c=Class.forName("com.flypie.Person"); //使用类加载器加载类 //1、找到类上的注解 if(c.isAnnotationPresent(Design.class)){ //判断类是否被指定注解注解 Design d=(Design) c.getAnnotation(Design.class); //拿到类上的指定注解实例 System.out.println(d.data()); } //2、找到方法上的注解 Method[] ms=c.getMethods(); for(Method m:ms){ if(m.isAnnotationPresent(Design.class)){ //判断方法是否被指定注解注解 Design d=m.getAnnotation(Design.class); //拿到类上的指定注解实例 System.out.println(d.data()); } } //3、另外一种方法 for(Method m:ms){ Annotation[] as=m.getAnnotations(); //拿到类上的注解集合 for(Annotation a:as){ if(a instanceof Design){ //判断指定注解 Design d=(Design) a; System.out.println(d.data()); } } } } }
相关文章推荐
- JAVA常用类库
- Java线程的中断
- Eclipse-----Eclipse各种小图标的含义
- Spring+SpringMVC+mybatis
- java后台的数据层数据组织
- Spring核心IOC容器实现分析
- ubuntu eclipse菜单栏消失的解决
- ubuntu eclipse启动报错
- Mybatis学习(4)与spring3集成
- weka+eclipse算法二次开发(2)
- java代码创建文件和文件夹
- JAVA系列(2)-JVM
- 学习Java技术Eclipse版本的选择
- JAVA系列(1)
- Java多线程编程
- 用 IntelliJ IDEA 15.x 创建并发布JavaWeb项目
- Spring+Maven+Dubbo+MyBatis+Linner+Handlebars—企业化Web开发环境搭建
- 如何利用Java获取进程的信息(通过tasklist和cmd与Windows进行交互)
- java加密、解密技术系列:Base64
- 怎样学习java?