java高级用法之注解和反射讲义
作者:CB 发布时间:2023-10-08 14:40:16
前言
反射和注解在java中偏高级用法,一般在各种框架中被广泛应用,文章简单介绍下反射和注解的用法,希望对你的工作学习有一定帮助
java注解
什么是注解
Java 注解也就是Annotation是从 Java5 开始引入的新技术
Annotation的作用:
不是程序本身,可以对程序作出解释
可以被其他程序(编译器等)读取
Annotation的格式:
注解以@注释名在代码中存在的,可以添加一些数值,例如SuppressWarnings(value=”unchecked”)
Annotation在里使用?
可以附加在package,class、method,filed等上面,相当与给他们添加了额外的辅助信息,我们可以通过反射机制编程实现对这些元数据的访问
元注解
元注解的作用就是负责注解其他注解,java定义了4个标准的meta-annotation类型,被用来提供对其他annotation类型作说明
这些类型和它们所支持的类在java.lang.annotation包中可以找到(@Target,@Retention,@Documented,@Inherited)
@Target:用于描述使用范围(注解在什么地方使用)
@Retetion:表示需要在什么级别保证该注释信息,用于描述注解的生命周期(source<class<runtime)
@Document:英文意思是文档。它的作用是能够将注解中的元素包含到 Javadoc 中去。
@Inherited:注解了的注解修饰了一个父类,如果他的子类没有被其他注解修饰,则它的子类也继承了父类的注解
自定义注解
使用@interface自定义注解时,自动继承了java.lang.annotation.Annotation接口
public class Test03 {
//注解可以显示赋值,如果没有默认值,一定要给注解赋值
@Myannotation2(name = "aj",schloos = {"机电学院"})
public void test(){
}
@MyAnnotation3("")
public void test2(){
}
}
@Target({ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@interface Myannotation2{
// 注解的参数,参数类型+参数名
String name() default "";
int age() default 0;
//如果默认值为-1 代表不存在
int id() default -1;
String[] schloos() ;
}
@Target({ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation3{
String value();
}
给代码加注解其实就是这么多,关键还是我们如何去读取注解,这就需要用到反射,下面重点介绍java反射
java反射
反射是java被视为动态语言的关键,反射机制允许程序在执行期借助Reflection API取得任何类的内部信息,并能直接操作任意对象内部熟悉及方法
Class c = Class.forName("java.lang.String")
加载完类之后,在堆内存的方法区就产生了一个Class类型的对象(一个类只有一个Class对象),这个对象就包含了完整的类的结构信息。我们可以通过这个对象看到类的结构。这个对象就像一面镜子,透过这个镜子看到类的结构,所以我们称之为:反射
Class类
对于每个类而言,JRE都为其保留一个不变的Class类型的对象,一个Class对象包含了特定某个结构的有关信息。
Class本身也是一个类
Class对象只能由系统建立对象
一个加载的类在jvm中只会有一个CLass实例
一个Class对象对应的是一个加载到jvm中的一个.class文件
每个类的实例都会记得自己是由哪个Class实例生成的
通过Class可以完整的得到一个类中的所有被加载的结构
Class类是Reflection的根源,针对任何你想动态加载、运行的类,唯有先获得相应的Class对象
Class类的常用方法
反射获取对象
public class Test02 {
public static void main(String[] args) throws ClassNotFoundException {
Person person = new Student();
System.out.println("这个人是"+person.name);
//通过对象获取
Class c1 = person.getClass();
System.out.println(c1.hashCode());
//通过forname获取
Class c2 = Class.forName("reflection.Student");
System.out.println(c2.hashCode());
//通过类名获取
Class c3 = Student.class;
System.out.println(c3.hashCode());
//获得父类类型
Class c4 = c1.getSuperclass();
System.out.println(c4);
}
}
@Data
class Person{
public String name;
public int age;
}
class Student extends Person{
public Student(){
this.name = "学生";
}
}
class Teacher extends Person{
public Teacher(){
this.name = "老师";
}
}
反射操作方法、属性
public class Test03 {
public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException {
Class c1 = Class.forName("reflection.Student");
Student student = (Student) c1.newInstance();
System.out.println(student.getName());
// 通过反射操作方法
Method setName = c1.getDeclaredMethod("setName", String.class);
setName.invoke(student, "zhangshan");
System.out.println(student.getName());
Student student1 = (Student) c1.newInstance();
Field name = c1.getDeclaredField("name");
//反射不能直接操作私有属性,需要手动关掉程序的安全检测,setAccessible(true)
name.setAccessible(true);
name.set(student1,"lisi");
System.out.println(student1.getName());
}
}
性能检测
public class Test04 {
public static void test01(){
User user = new User();
long startTime = System.currentTimeMillis();
for (int i = 0; i <1000000000 ; i++) {
user.getName();
}
long endTime = System.currentTimeMillis();
System.out.println(endTime - startTime +"ms");
}
public static void test02() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
User user = new User();
long startTime = System.currentTimeMillis();
Class c1 = user.getClass();
Method getName = c1.getDeclaredMethod("getName", null);
for (int i = 0; i <1000000000 ; i++) {
getName.invoke(user, null);
}
long endTime = System.currentTimeMillis();
System.out.println(endTime - startTime +"ms");
}
public static void test03() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
User user = new User();
long startTime = System.currentTimeMillis();
Class c1 = user.getClass();
Method getName = c1.getDeclaredMethod("getName", null);
getName.setAccessible(true);
for (int i = 0; i <1000000000 ; i++) {
getName.invoke(user, null);
}
long endTime = System.currentTimeMillis();
System.out.println(endTime - startTime +"ms");
}
public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
test01();
test02();
test03();
}
}
反射操作注解
public class Test05 {
public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException {
Class<?> c1 = Class.forName("reflection.Customer");
// 通过反射获取注解
Annotation[] annotations = c1.getAnnotations();
for (Annotation annotation:annotations){
System.out.println(annotation);
}
// 获取注解的值
TableAnnotation annotation = c1.getAnnotation(TableAnnotation.class);
System.out.println(annotation.value());
//获取类指定注解
Field id = c1.getDeclaredField("id");
FiledAnnotation annotation1 = id.getAnnotation(FiledAnnotation.class);
System.out.println(annotation1.columnName());
System.out.println(annotation1.length());
System.out.println(annotation1.type());
}
}
//类注解
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface TableAnnotation{
String value();
}
@Data
@TableAnnotation("db_customer")
class Customer {
@FiledAnnotation(columnName="id",type = "Long",length =10)
private Long id;
@FiledAnnotation(columnName="age",type = "int",length =10)
private int age;
@FiledAnnotation(columnName="name",type = "String",length =10)
private String name;
}
//方法注解
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface FiledAnnotation{
String columnName();
String type();
int length();
}
总结
来源:http://cbaj.gitee.io/blog/2021/05/09/java-%E6%B3%A8%E8%A7%A3%E5%92%8C%E5%8F%8D%E5%B0%84%E8%AE%B2%E4%B9%89/


猜你喜欢
- 本文实例为大家分享了Spring AOP实现记录操作日志的具体代码,供大家参考,具体内容如下1 添加maven依赖<dependenc
- import java.util.Calendar;import java.util.Date;public class Matrix {&
- 1.加入jackson的jar包2.在响应的方法上加上@ResponseBody:把java对象转化为json对象3.方法的返回值可以是对象
- 指针是什么?指针(Pointer)是一个特殊的变量,它里面存储的数值被解释成为内存里的一个地址。换句话说就是可以通过指针找到以它为地址的内存
- 本文实例为大家分享了android实现简单拼图游戏的具体代码,供大家参考,具体内容如下1.2.//使用回调接口,首先初始化pintuview
- 本文实例为大家分享了Android点击获取验证码倒计时的具体代码,供大家参考,具体内容如下package com.loaderman.cou
- 短网址(Short URL) ,顾名思义就是看起来很短的网址。自从twitter推出短网址服务以后,各大互联网公司都推出了自己的短网址服务。
- 导言目前截屏的方法很多,root不适用,要么其他方法就是有局限性,而其中官方给出的方案最好—MediaProjection介绍Android
- 配置Servlet的方法有俩种,分别是传统web.xml文档中部署servlet和注解方式部署servlet,下面就先一起来学习 * 解方式部
- 什么是fescar?关于fescar的详细介绍,请参阅fescar wiki。传统的2PC提交协议,会持有一个全局性的锁,所有局部事务预提交
- 本文实例为大家分享了android通过NFC读取卡号的具体代码,供大家参考,具体内容如下1.获取权限<uses-permission
- 在Android开发中我们经常有这样的需求,从服务器上下载xml或者JSON类型的数据,其中包括一些图片资源,本demo模拟了这个需求,从网
- springBoot是java开发中会经常用到的框架,那么在实际项目中项目配置了springBoot框架,应该如何在项目中读取配置文件中的参
- 首先我们上图: xml的代码如下,用于编写按钮:<?xml version="1.0" encoding
- 程序目的从java字节码层理解,为何i = i++后,结果是+1之前的数值。而i=++i后,结果是+1之后的值。关键指令iload_<
- 本文实例为大家分享了C#仿微信红包功能的具体代码,供大家参考,具体内容如下Program.cs代码:class Program { &nbs
- 前言工作中遇到nodejs端通过aes加密,安卓客户端Java解密,同样nodejs也需要解密安卓客户端加密过来的内容,发现两个加密结果不一
- 这个功能,大家也都可以去百度以下,千篇一律都自己写的(抄的)封装好的公共类,此处还是得膜拜下原创的大佬,可以花时间去搞这个,我看着都头皮发麻
- 1.普通轮询算 * 询(Round Robin,RR)是依次将用户的访问请求,按循环顺序分配到web服务节点上,从1开始到最后一台服务器节点结
- 用java的框架和面板的知识做的一个展示月食过程的小程序。这里的想法就是先把背景设置成黑色,然后画一个黄色的圆作为月亮,接着画一个黑色的圆,