java自定义注解类

一、前言

  今天阅读帆哥代码的时候,看到了之前没有见过的新东西, 比如java自定义注解类,如何获取注解,如何反射内部类,this$0是什么意思? 于是乎,学习并整理了一下。

二、代码示例

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Field;

//自定义注解类 @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) @
interface MyAnnotation {String name() default "hjzgg"; }public class Main {public Main(Class cls) {Field[] fields = cls.getDeclaredFields();TestAnnotation obj = null;try {obj = (TestAnnotation)cls.getConstructors()[0].newInstance(this);//获取内部类对象} catch (Exception e) {e.printStackTrace();}for(Field field : fields) {System.out.println(field.getName() + " " + field.getType().getName());if(!field.getName().equals("this$0")) { MyAnnotation annotation = field.getAnnotation(MyAnnotation.class);//获取注解类String name = annotation.name();field.setAccessible(true);try {switch(name) {case "hjzgg":switch(field.getType().getName()) {case "int":case "java.lang.Integer":field.set(obj, 555);break;case "java.lang.String":field.set(obj, "hehe");break;}break;case "lxkdd":switch(field.getType().getName()) {case "int":case "java.lang.Integer":field.set(obj, 555);break;case "java.lang.String":field.set(obj, "hehe");break;}break;default:break;}} catch (Exception e) {e.printStackTrace();}}}System.out.println(obj);}public static void main(String[] args) throws InstantiationException, IllegalAccessException {new Main(TestAnnotation.class);}class TestAnnotation{public TestAnnotation(){}@MyAnnotation(name="lxkdd")private int x;@MyAnnotationprivate String y;public int getX() {return x;}public void setX(int x) {this.x = x;}public String getY() {return y;}public void setY(String y) {this.y = y;}@Overridepublic String toString() {return "x: " + x + ", y: " + y; }} }

三、代码分析

  1.如何编写自定义注解

public @interface MyAnnotation {   String value() default "hahaha";   
}  

  感觉等价于

public class MyAnnotation extends java.lang.annotation.Annotation{   private String value = "hahaha";   public void setValue(String value){   this.value = value;   }   public String getValue(){   return value;   }   
} 

  自定义注解类规则

  @interface实际上是继承了java.lang.annotation.Annotation,所以定义annotation时不能继承其他annotation或interface. java.lang.annotation.Retention告诉编译器如何对待 Annotation,使用Retention时,需要提供java.lang.annotation.RetentionPolicy的枚举值.

public enum RetentionPolicy {   SOURCE, // 编译器处理完Annotation后不存储在class中   CLASS, // 编译器把Annotation存储在class中,这是默认值   RUNTIME // 编译器把Annotation存储在class中,可以由虚拟机读取,反射需要   
}   

    java.lang.annotation.Target告诉编译器Annotation使用在哪些地方,使用需要指定java.lang.annotation.ElementType的枚举值.

public enum ElementType {   TYPE, // 指定适用点为 class, interface, enum   FIELD, // 指定适用点为 field   METHOD, // 指定适用点为 method   PARAMETER, // 指定适用点为 method 的 parameter   CONSTRUCTOR, // 指定适用点为 constructor   LOCAL_VARIABLE, // 指定使用点为 局部变量   ANNOTATION_TYPE, //指定适用点为 annotation 类型   PACKAGE // 指定适用点为 package   
}   

    java.lang.annotation.Documented用于指定该Annotation是否可以写入javadoc中. 
    java.lang.annotation.Inherited用于指定该Annotation用于父类时是否能够被子类继承. 

  示例

import java.lang.annotation.ElementType;   
import java.lang.annotation.Retention;   
import java.lang.annotation.RetentionPolicy;   
import java.lang.annotation.Target;   @Documented  //这个Annotation可以被写入javadoc   
@Inherited       //这个Annotation 可以被继承   
@Target({ElementType.CONSTRUCTOR,ElementType.METHOD}) //表示这个Annotation只能用于注释 构造子和方法   
@Retention(RetentionPolicy.CLASS) //表示这个Annotation存入class但vm不读取   
public @interface MyAnnotation {   String value() default "hahaha";   
}  

  2.如何获取自定义注解

   java.lang.reflect.AnnotatedElement接口提供了四个方法来访问Annotation

public Annotation getAnnotation(Class annotationType);   
public Annotation[] getAnnotations();   
public Annotation[] getDeclaredAnnotations();   
public boolean isAnnotationPresent(Class annotationType);  

   来自:http://blog.csdn.net/foamflower/article/details/5946451

   Class、Constructor、Field、Method、Package等都实现了该接口,可以通过这些方法访问Annotation信息,前提是要访问的Annotation指定Retention为RUNTIME. 
     Java内置的annotation有Override Deprecated SuppressWarnings. 
     Override只用于方法,它指明注释的方法重写父类的方法,如果不是,则编译器报错. 
     Deprecated指明该方法不建议使用.
     SuppressWarnings告诉编译器:我知道我的代码没问题.

  3.this$0是什么意思?

public class Outer {//this$0 public class FirstInner {//this$1 public class SecondInner {//this$2 public class ThirdInner { } } } 
}

  说一个场景:当我们拿到了一个内部类的对象Inner,但是又想获取其对应的外部类Outer,那么就可以通过this$0来获取。this$0就是内部类所自动保留的一个指向所在外部类的引用。 

    //通过工具获取到Inner实例对象 Outer.Inner inner = getInner(); //获取内部类Inner的一个字段this$0信息 //this$0特指该内部类所在的外部类的引用,不需要手动定义,编译时自动加上 Filed outerField = inner.getClass().getDeclaredField("this$0"); //this$0是私有的,提升访问权限 outerField.setAccessible(true); //拿到该字段上的实例值 Outer outer = (Outer)outerField.get(inner); 

  4.java如何反射内部类

Class<?> cls = Class.forName("package.OuterClass$InnerClass"); or Class<?> cls = OuterClass.InnerClass.class;
(1)OuterClass.InnerClass obj = (OuterClass.InnerClass)cls.getConstructors()[0].newInstance(new OuterClass()); 
(2)OuterClass.InnerClass obj = (OuterClass.InnerClass)cls.getConstructor(OuterClass.class).newInstance(new OuterClass());

  由此可见,内部类的无参构造器在通过反射机制获取时,要指定其父类参数才可以获得,否则将报如下异常:

java.lang.NoSuchMethodException: com.hjzgg.OuterClass$InnerClass.<init>()at java.lang.Class.getConstructor0(Class.java:3082)at java.lang.Class.getConstructor(Class.java:1825)

 

转载于:https://www.cnblogs.com/hujunzheng/p/5719611.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/531292.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

解决cookie跨域访问

一、前言 随着项目模块越来越多&#xff0c;很多模块现在都是独立部署。模块之间的交流有时可能会通过cookie来完成。比如说门户和应用&#xff0c;分别部署在不同的机器或者web容器中&#xff0c;假如用户登陆之后会在浏览器客户端写入cookie&#xff08;记录着用户上下文信息…

React使用antd Table生成层级多选组件

一、需求 用户对不同的应用需要有不同的权限&#xff0c;用户一般和角色关联在一起&#xff0c;新建角色的时候会选择该角色对应的应用&#xff0c;然后对应用分配权限。于是写了一种实现的方式。首先应用是一个二级树&#xff0c;一级表示的是应用分组&#xff0c;二级表示的是…

junit4进行单元测试

一、前言 提供服务的时候&#xff0c;为了保证服务的正确性&#xff0c;有时候需要编写测试类验证其正确性和可用性。以前的做法都是自己简单写一个控制层&#xff0c;然后在控制层里调用服务并测试&#xff0c;这样做虽然能够达到测试的目的&#xff0c;但是太不专业了。还是老…

快速搭建springmvc+spring data jpa工程

一、前言 这里简单讲述一下如何快速使用springmvc和spring data jpa搭建后台开发工程&#xff0c;并提供了一个简单的demo作为参考。 二、创建maven工程 http://www.cnblogs.com/hujunzheng/p/5450255.html 三、配置文件说明 1.application.properties jdbc.drivercom.mysql.jd…

dubbo服务提供与消费

一、前言 项目中用到了Dubbo&#xff0c;临时抱大腿&#xff0c;学习了dubbo的简单实用方法。现在就来总结一下dubbo如何提供服务&#xff0c;如何消费服务&#xff0c;并做了一个简单的demo作为参考。 二、Dubbo是什么 Dubbo是一个分布式服务框架&#xff0c;致力于提供高性能…

git亲测命令

一、Git新建本地分支与远程分支关联问题 git checkout -b branch_name origin/branch_name 或者 git branch --set-upstream branch_name origin/branch_name 或者 git branch branch_name git branch --set-upstream-toorigin/branch_name branch_name 二、查看本地分支所关…

mysql 7下载安装及问题解决

mysql 7安装及问题解决 一、mysql下载 下载地址&#xff1a;https://www.mysql.com/downloads/Community (GPL) DownloadsMySQL Community Server (GPL)Windows (x86, 64-bit), ZIP ArchiveNo thanks, just start my download.二、mysql安装 解压到指定目录在mysql bin目录下打…

RestTemplate发送请求并携带header信息

1、使用restTemplate的postForObject方法 注&#xff1a;目前没有发现发送携带header信息的getForObject方法。 HttpHeaders headers new HttpHeaders(); Enumeration<String> headerNames request.getHeaderNames(); while (headerNames.hasMoreElements()) {String k…

工作中常用到的命令

linux zip 和 unzip http://blog.csdn.net/shenyunsese/article/details/17556089 linux 查看日志 http://blog.chinaunix.net/uid-15463753-id-2943532.html linux 删除 http://www.jb51.net/LINUXjishu/179430.html linux查看末尾日志&#xff08;tail -f&#xff09; http:/…

tomcat开发远程调试端口以及利用eclipse进行远程调试

一、tomcat开发远程调试端口 方法1 WIN系统 在catalina.bat里&#xff1a;   SET CATALINA_OPTS-server -Xdebug -Xnoagent -Djava.compilerNONE -Xrunjdwp:transportdt_socket,servery,suspendn,address8899   Linux系统 在catalina.sh里&#xff1a;   CATALINA_OPTS&q…

webpack+react+redux+es6开发模式

一、预备知识 node, npm, react, redux, es6, webpack 二、学习资源 ECMAScript 6入门 React和Redux的连接react-redux Redux 入门教程 redux middleware 详解 Redux研究 React 入门实例教程 webpack学习demo NPM 使用介绍 三、工程搭建 之前有写过 webpackreactes6开发模式…

fiddler发送post请求

1.指定为 post 请求&#xff0c;输入 url Content-Type: application/x-www-form-urlencoded;charsetutf-8 request body中的参数格式&#xff1a;userNameadminicxp&userPassword123qwe!# 这种方式可以用 request.getParameter的方式来获得。 2.指定为 post 请求&#xff…

基于spring注解AOP的异常处理

一、前言 项目刚刚开发的时候&#xff0c;并没有做好充足的准备。开发到一定程度的时候才会想到还有一些问题没有解决。就比如今天我要说的一个问题&#xff1a;异常的处理。写程序的时候一般都会通过try...catch...finally对异常进行处理&#xff0c;但是我们真的能在写程序的…

Kettle之数据抽取、转换、装载

Kettle 官网 ETL利器Kettle实战应用解析系列 利用kettle组件导入excel文件到数据库 kettle中实现动态SQL查询 java中调用kettle转换文件 kettle 7.x版本下载&#xff1a;https://pan.baidu.com/s/1nvnzzCH  密码&#xff1a;6f5c mac 下运行spoon.sh,  windows下为spoon.bat…

webpack+react+redux+es6开发模式---续

一、前言 之前介绍了webpackreactreduxes6开发模式 &#xff0c;这个项目对于一个独立的功能节点来说是没有问题的。假如伴随着源源不断的需求&#xff0c;前段项目会涌现出更多的功能节点&#xff0c;需要独立部署运行。为了更好地管理这些独立的功能节点&#xff0c;我们需要…

JdbcTemplate使用小结

org.springframework.jdbc.core.JdbcTemplate.query(String sql, Object[] args, RowMapper<StaffUnionVO> rowMapper) throws DataAccessException 1.自定义rowMapper public class StaffUnionVO implements RowMapper<StaffUnionVO>, Serializable {private stat…

RabbitMQ安装和使用(和Spring集成)

一、安装Rabbit MQ   Rabbit MQ 是建立在强大的Erlang OTP平台上&#xff0c;因此安装Rabbit MQ的前提是安装Erlang。通过下面两个连接下载安装3.2.3 版本&#xff1a; 下载并安装 Eralng OTP For Windows (vR16B03)运行安装 Rabbit MQ Server Windows Installer (v3.2.3)具体…

单点登录实现(spring session+redis完成session共享)

一、前言 项目中用到的SSO&#xff0c;使用开源框架cas做的。简单的了解了一下cas&#xff0c;并学习了一下 单点登录的原理&#xff0c;有兴趣的同学也可以学习一下&#xff0c;写个demo玩一玩。 二、工程结构 我模拟了 sso的客户端和sso的服务端&#xff0c; sso-core中主要是…

maven deploy上传私服出错

error 内容如下 Failed to execute goal org.apache.maven.plugins:maven-deploy-plugin:2.5: deploy (default-deploy) on project XXX pom文件增加如下配置 <build><plugins><plugin><groupId>org.apache.maven.plugins</groupId><artifa…

加密策略

一、前言 这两天研究了一下项目中的密码加密&#xff0c;可以说得上是学到了很多。下面来大致说一下。 二、常用加密 1.单向加密算法 单向加密算法主要用来验证数据传输的过程中&#xff0c;是否被篡改过。 BASE64 严格地说&#xff0c;属于编码格式&#xff0c;而非加密算法 …