java注解和反射讲义

news/2024/5/19 6:39:56 标签: java, spring, 反射, 编程语言

反射和注解在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类的常用方法

![image-20210502212459742](/Users/cb/Library/Application Support/typora-user-images/image-20210502212459742.png)

反射获取对象

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://www.niftyadmin.cn/n/1227487.html

相关文章

ubuntu下安装lxml报错_Ubuntu下GDAL编译与安装

1.GDAL下载DownloadSource - GDAL​trac.osgeo.org2.安装将安装包拷贝至usr/local下cd usr/local tar -zxvf gdal-2.3.0.tar.gz cd usr/local/gdal-2.3.0 ./configure sudo make sudo make install运行gadlinfo&#xff0c;报错gdalinfo: error while loading shared libraries…

一文带你jvm由浅入深

JVM是Java Virtual Machine&#xff08;Java 虚拟机 &#xff09;的缩写&#xff0c;JVM是一种用于计算设备的规范&#xff0c;它是一个虚构出来的计算机&#xff0c;是通过在实际的计算机上仿真模拟各种计算机功能来实现的。引入Java语言虚拟机后&#xff0c;Java语言在不同平…

大数据技术与实践

大数据概述 定义&#xff1a;   大数据一词由英文“big data”翻译而来&#xff0c;是最近几年兴起的概念&#xff0c;目前还没有一个统一的定义。相比于过去的“信息爆炸”的概念&#xff0c;它更强调数据量的“大”。 大数据的4V特征 数据量大Volume、变化速度快Velocity…

python知识图谱关系抽取算法_一种适用图文知识图谱的关系抽取方法与流程

本发明涉及信息处理领域&#xff0c;特别涉及图像目标检测以及知识图谱中的关系抽取算法。 背景技术&#xff1a; 图像目标检测目的是在于检测图像中包含的所有物体&#xff0c;基本做法是将图像划分区域后再对每个区域进行图像分类。 知识图谱中的一个关键技术就是关系抽取算法…

python社区发现_网络算法系列之社区发现(一):标签传播算法

社区发现简介 社区发现问题实际上是从子图分割的问题演变而来。在社交网络中&#xff0c;有些用户连接非常紧密&#xff0c;有些用户连接较为稀疏&#xff0c;这些连接紧密的用户可以看做一个社区&#xff0c;而社区之间连接较为稀疏。下图就展示了一个社区发现。目前的社区发现…

沉降观测曲线图 沉降观测汇总_南水北调中线干渠藻类残体颗粒与模型材料沉降特性研究...

原标题&#xff1a;藻类残体颗粒的沉降特性与模型材料选择摘要&#xff1a;南水北调中线干渠中藻类残体随流运动,容易在退水闸、分水口等突扩断面位置沉积,需要经常进行清淤工作。本文应用PTV粒子追踪测速技术,通过1组工况的藻类残体颗粒静水沉降试验和24组工况的不同模型材料、…

西瓜数据集3.0_在线教育领域数据统计分析

一、这个数据集对应的产品与国内哪款产品类似&#xff1f;该数据集与各大在线教育企业官网选课界面中K12模块的内容相似&#xff0c;具体产品如&#xff1a;“学而思网校”、“新东方”等。二、数据集数据来源地址&#xff1a;通过某爬虫工具爬取沪江网校中小幼教育培训班官网数…

hive 窗口函数_Flink的窗口类型详解

这是我的第87篇原创窗口函数真奇妙&#xff0c;聚合计算快又好&#xff0c;数据分析宝中宝&#xff0c;表哥表妹不能少&#xff0c;不&#xff01;能&#xff01;少&#xff01;在我刚入行的时候&#xff0c;还不懂啥窗口函数&#xff0c;想出一张报表那叫一个费劲啊&#xff0…