【注解和反射】--05 反射的性能对比、反射操作泛型和注解

news/2024/7/5 2:01:01

反射

05 性能对比分析

下面对比了通过普通new方式、反射方式及关闭Java语言安全检测的反射方式三种情况下,程序的性能(所需时间)。

package com.duo.reflection;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

//性能测试
public class Test8 {
    //1.普通方式new
    public static void test1() {
        Person person = new Person();

        long startTime = System.currentTimeMillis();
        for (int i = 0; i < 100000000; i++) {
            String name = person.getName();
        }
        long endTime = System.currentTimeMillis();

        System.out.println("普通方式(new)调用执行1亿次所需时间:" + (endTime - startTime) + "ms");
    }

    //2.反射方式调用
    public static void test2() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        Person person = new Person();
        Class<? extends Person> c1 = person.getClass();

        Method getName = c1.getMethod("getName",  null);

        long startTime = System.currentTimeMillis();
        for (int i = 0; i < 100000000; i++) {
            getName.invoke(person, (Object[]) null);
        }
        long endTime = System.currentTimeMillis();

        System.out.println("反射方式调用执行1亿次所需时间:" + (endTime - startTime) + "ms");
    }

    //3.关闭Java语言安全检查调用
    public static void test3() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        Person person = new Person();
        Class<? extends Person> c1 = person.getClass();

        Method getName = c1.getMethod("getName",  null);
        getName.setAccessible(true);

        long startTime = System.currentTimeMillis();
        for (int i = 0; i < 100000000; i++) {
            getName.invoke(person, (Object[]) null);
        }
        long endTime = System.currentTimeMillis();

        System.out.println("关闭安全检测以反射方式调用执行1亿次所需时间:" + (endTime - startTime) + "ms");
    }

    public static void main(String[] args) throws InvocationTargetException, NoSuchMethodException, IllegalAccessException {
        test1();
        test2();
        test3();
    }
}

运行结果:

图1

由此可见,通过反射方式调用执行会影响程序效率,而采用了setAccessible()关闭语言安全检测之后可以提高效率。

06 反射操作泛型

  • Java采用泛型擦除的机制来引入泛型,Java中的泛型仅仅是给编译器javac使用的,确保数据的安全性和免去强制类型转换问题,但是一旦编译完成,所有和泛型有关的类型全部擦除

  • 为了通过反射操作这些类型,Java新增了ParameterizedType,GenericArrayType,TypeVariable和WildcardType几种类型来代表不能被归一到Class类中的类型但又和原始类型齐名的类型

    • ParameterizedType:表示一种参数化类型,例如Collection
    • GenericArrayType:表示一种元素类型是参数化类型或者类型变量的数组类型
    • TypeVariable:是各种类型变量的公共父接口
    • WildcardType:代表一种通配符类型表达式
  • 获取泛型信息:

package com.duo.reflection;

import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;

//通过反射获取泛型
public class Test9 {

    public void test01(Map<String, Person> map, List<Person> list) {}

    public Map<String, Person> test02() {
        System.out.println("test02");
        return null;
    }

    public static void main(String[] args) throws NoSuchMethodException {
        Method method = Test9.class.getMethod("test01", Map.class, List.class);
        Type[] genericParameterTypes = method.getGenericParameterTypes();  //获得泛型的参数类型

        for (Type genericParameterType : genericParameterTypes) {
            System.out.println("#" + genericParameterType);

            //instanceof:用来在运行时指出对象是否是特定类的一个实例
            if (genericParameterType instanceof ParameterizedType) {
                Type[] actualTypeArguments = ((ParameterizedType) genericParameterType).getActualTypeArguments();
                for (Type actualTypeArgument : actualTypeArguments) {
                    System.out.println(actualTypeArgument);
                }
            }
        }

        System.out.println("==========================");
        method = Test9.class.getMethod("test02");
        Type genericReturnType = method.getGenericReturnType();  //获得泛型返回值类型

        if (genericReturnType instanceof ParameterizedType) {
            Type[] actualTypeArguments = ((ParameterizedType) genericReturnType).getActualTypeArguments();
            for (Type actualTypeArgument : actualTypeArguments) {
                System.out.println(actualTypeArgument);
            }
        }
    }
}

运行结果:

图2

07 反射操作注解

  • getAnnotations

  • getAnnotation

  • 了解什么是ORM?

    • Object relationship Mapping --> 对象关系映射

    • class Student {
      	int id;
      	String name;
      	int age;
      }
      
    • 上述对应:

      idnameage
      001Li32
      002Wang24
    • 即,类和表结构对应、属性和字段对应、对象和记录对应

  • 反射操作注解:

package com.duo.reflection;

import java.lang.annotation.*;
import java.lang.reflect.Field;

//反射操作注解
public class Test10 {

    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException {
        Class<?> c1 = Class.forName("com.duo.reflection.men");

        //通过反射获得(类名的)注解
        Annotation[] annotations = c1.getAnnotations();
        for (Annotation annotation : annotations) {
            System.out.println(annotation);
        }

        //获得(类名的)注解的value值
        Table annotation = c1.getAnnotation(Table.class);
        String value = annotation.value();
        System.out.println(value);

        //获得类指定的注解
        Field id = c1.getDeclaredField("name");
        Attribute annotation1 = id.getAnnotation(Attribute.class);
        System.out.println(annotation1.columnName());
        System.out.println(annotation1.type());
        System.out.println(annotation1.length());
    }
}

@Table("database_men")
class men {

    @Attribute(columnName = "id", type = "int", length = 10)
    private int id;
    @Attribute(columnName = "age", type = "int", length = 10)
    private int age;
    @Attribute(columnName = "name", type = "varchar", length = 3)
    private String name;

    public men() {}

    public men(int id, int age, String name) {
        this.id = id;
        this.age = age;
        this.name = name;
    }

    public int getId() {return id;}

    public void setId(int id) {this.id = id;}

    public int getAge() {return age;}

    public void setAge(int age) {this.age = age;}

    public String getName() {return name;}

    public void setName(String name) {this.name = name;}

    @Override
    public String toString() {
        return "man{" +
                "id=" + id +
                ", age=" + age +
                ", name='" + name + '\'' +
                '}';
    }
}

//类名的注解
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface Table {
    String value();
}

//属性的注解
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface Attribute {
    String columnName();
    String type();
    int length();
}

运行结果:

图3



http://lihuaxi.xjx100.cn/news/1898656.html

相关文章

【深度学习目标检测】八、基于yolov5的抽烟识别(python,深度学习)

YOLOv5是目标检测领域一种非常优秀的模型&#xff0c;其具有以下几个优势&#xff1a; 1. 高精度&#xff1a;YOLOv5相比于其前身YOLOv4&#xff0c;在目标检测精度上有了显著的提升。YOLOv5使用了一系列的改进&#xff0c;如更深的网络结构、更多的特征层和更高分辨率的输入图…

【Redis】AOF 基础

因为 Redis AOF 的实现有些绕, 就分成 2 篇进行分析, 本篇主要是介绍一下 AOF 的一些特性和依赖的其他函数的逻辑,为下一篇 (Redis AOF 源码) 源码分析做一些铺垫。 AOF 全称: Append Only File, 是 Redis 提供了一种数据保存模式, Redis 默认不开启。 AOF 采用日志的形式来记…

DevOps常用工具全家桶,实现高效运维和交付

专栏集锦&#xff0c;大佬们可以收藏以备不时之需&#xff1a; Spring Cloud 专栏&#xff1a;http://t.csdnimg.cn/WDmJ9 Python 专栏&#xff1a;http://t.csdnimg.cn/hMwPR Redis 专栏&#xff1a;http://t.csdnimg.cn/Qq0Xc TensorFlow 专栏&#xff1a;http://t.csdni…

【二分查找】自写二分函数的总结

作者推荐 【动态规划】【广度优先搜索】LeetCode:2617 网格图中最少访问的格子数 本文涉及的基础知识点 二分查找算法合集 自写二分函数 的封装 我暂时只发现两种&#xff1a; 一&#xff0c;在左闭右开的区间寻找最后一个符合条件的元素&#xff0c;我封装成FindEnd函数。…

设计模式—装饰模式

与其明天开始&#xff0c;不如现在行动&#xff01; 文章目录 装饰模式—穿衣服&#x1f48e;总结 装饰模式—穿衣服 装饰模式&#xff08;Decorator&#xff09;可以动态的给对象添加一些额外的职责。 Component是定义一个对象接口&#xff0c;可以给这些对象动态地添加职责。…

HPV治疗期间如何预防重复感染?谭巍主任讲述具体方法

众所周知&#xff0c;人乳头瘤病毒(HPV)是一种常见的性传播疾病&#xff0c;感染后可能会引起生殖器疣、宫颈癌等疾病。在治疗期间&#xff0c;预防重复感染非常重要。今日将介绍一些预防HPV重复感染的方法。 1. 杜绝不洁性行为 在治疗期间&#xff0c;患者应该避免与感染HPV…

FLStudio2024完整版水果音乐编曲制作软件

FL Studio2024是款专业的音频录制编辑软件&#xff0c;可以针对作曲者的要求编辑出不同音律的节奏&#xff0c;例如鼓、镲、锣、钢琴、笛、大提琴等等任何乐器的节奏律动。FL Studio目前在中国已经受到广大制作人喜爱&#xff0c;使用它制作的音乐作品也已经数不胜数&#xff0…

下午好~ 我的论文【CV边角料】(第三期)

文章目录 CV边角料Pixel ShuffleSENetCBAMGlobal Context Block (GC)Criss-Cross Attention modules (CC) CV边角料 Pixel Shuffle Real-Time Single Image and Video Super-Resolution Using an Efficient Sub-Pixel Convolutional Neural Network pixelshuffle算法的实现流…