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

反射

05 性能对比分析

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

package com.duo.reflection;import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;//性能测试
public class Test8 {//1.普通方式newpublic 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;}@Overridepublic 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://www.mzph.cn/news/229235.shtml

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

相关文章

WPF——命令commond的实现方法

命令commond的实现方法 属性通知的方式 鼠标监听绑定事件 行为&#xff1a;可以传递界面控件的参数 第一种&#xff1a; 第二种&#xff1a; 附加属性 propa&#xff1a;附加属性快捷方式

第25节: Vue3 带组件

在UniApp中使用Vue3框架时&#xff0c;你可以使用组件来封装可复用的代码块&#xff0c;并在需要的地方进行渲染。下面是一个示例&#xff0c;演示了如何在UniApp中使用Vue3框架使用带组件&#xff1a; <template> <view> <button click"toggleActive&q…

解决引入外部文件(图片、js等)出现 403 net::ERR_ABORTED 的问题

页面中引入外网的连接资源&#xff0c;会产生一个新的http请求。为了安全&#xff08;URL里可能包含用户信息&#xff09;&#xff0c;浏览器通常都会给这写请求头加上表示来源的referrer 字段。 因此&#xff0c;此时咱们须要隐藏外部连接中的referrer&#xff0c;在head标签…

React的JSX

React JSX 大家好,欢迎来到 React JSX 的课程。在这一课中,我们将学习如何在 React 中使用 JSX。 什么是 JSX? JSX 是一种 JavaScript 的语法扩展,它看起来很像 XML。 const element = <h1>Hello, world!</h1>;这种看起来可能有些奇怪的标签语法既不是字符…

CCNP课程实验-OSPF-CFG

目录 实验条件网络拓朴需求 配置实现基础配置1. 配置所有设备的IP地址 实现目标1. 要求按照下列标准配置一个OSPF网络。 路由协议采用OSPF&#xff0c;进程ID为89 &#xff0c;RID为loopback0地址。3. R4/R5/R6相连的三个站点链路OSPF网络类型配置成广播型&#xff0c;其中R5路…

springboot使用EasyExcel导出数据

springboot使用EasyExcel导出数据 简介&#xff1a;本文主要描述使用EasyExcel导出数据的简单流程&#xff0c;事实上企业需求一般都比较简单&#xff0c;就是表单数据输出到Excel即可&#xff0c;如果数据量大的话&#xff0c;为了避免占用内存过高或者OOM&#xff0c;使用多…

Android Studio好用的插件推荐

目录 一、插件推荐 二、如何下载 1.点击File—>Settings ​2.点击Plugins然后进行搜索下载 三、Android Studio 模板 一、插件推荐 这个插件可以为您自动生成Parcelable代码。Parcelable是一种用于在Android组件之间传递自定义对象的机制&#xff0c;但手动编写Parcela…

[python]用python获取EXCEL文件内容并保存到DBC

目录 关键词平台说明背景所需库实现过程方法1.1.安装相关库2.代码实现 关键词 python、excel、DBC、openpyxl 平台说明 项目Valuepython版本3.6 背景 在搭建自动化测试平台的时候经常会提取DBC文件中的信息并保存为excel或者其他文件格式&#xff0c;用于自动化测试。本文…

Flowable-源码分析-2启动

引擎启动流程如图 // ProcessEngineFactoryBean.getObjectpublic ProcessEngine getObject() throws Exception {// 如果 processEngine 为空if (processEngine null) {// 初始化表达式管理器initializeExpressionManager();// 初始化事务外部管理initializeTransactionExtern…

​optparse --- 命令行选项的解析器​

源代码&#xff1a; Lib/optparse.py 3.2 版后已移除: optparse 模块已被弃用并且将不再继续开发&#xff1b;开发将转至 argparse 模块进行。 optparse 是一个相比原有 getopt 模块更为方便、灵活和强大的命令行选项解析库。 optparse 使用更为显明的命令行解析风格&#xff…

HTML面试题

HTML面试题 什么是HTML&#xff1f;它是用于什么目的的&#xff1f; HTML代表超文本标记语言&#xff08;HyperText Markup Language&#xff09;&#xff0c;它是一种用于创建网页的标记语言。HTML使用标签来定义网页的结构、内容和样式。 HTML5与HTML4有什么不同&#xff1f…

Linux---用户相关操作

1. 创建用户 命令说明useradd创建(添加)用户 useradd命令选项: 选项说明-m自动创建用户主目录,主目录的名字就是用户名-g指定用户所属的用户组&#xff0c;默认不指定会自动创建一个同名的用户组 创建用户效果图: 查看所有用户信息的文件效果图: 说明: useradd 命令的使用…

嵌入式中的门电路详讲

NOT门电路 NOT(非门)是数字逻辑电路中的一种基本逻辑门,也称为反相器。它执行的是逻辑非操作,即将输入信号取反。NOT门具有一个输入和一个输出。 A输入,B输出,以下是真值表: A B 0 1 1 0 AND门电路 AND(与门)是数字逻辑电路中的一种基本逻辑门,用于执行逻辑与操作。…

【运维笔记】mvware centos挂载共享文件夹

安装mvware-tools 这里用的centos安装 yum install open-vm-tools 设置共享文件夹 依次点击&#xff1a;选项-共享文件夹-总是启用-添加&#xff0c;安装添加向导操作添加自己想共享的文件夹后。成功后即可在文件夹栏看到自己共享的文件夹 挂载文件夹 临时挂载 启动虚拟机&…

Javaweb考前复习冲刺(不断更新版)

Javaweb考前复习冲刺 第一章&#xff1a; JavaWeb 入门 JavaWeb是指&#xff1a;以Java作为后台语言的项目工程。 javaweb项目创建的过程&#xff1a; 首先集成Tomcat服务器环境新建dynamic web project部署工程运行 路由含义&#xff1a; ​ http://localhost:8080/工程…

技术分析测试

文章目录 概要整体架构流程技术名词解释技术细节小结 概要 提示&#xff1a;这里可以添加技术概要 例如&#xff1a; openAI 的 GPT 大模型的发展历程。 整体架构流程 提示&#xff1a;这里可以添加技术整体架构 例如&#xff1a; 在语言模型中&#xff0c;编码器和解码器都…

Leetcode刷题笔记题解(C++):224. 基本计算器

思路&#xff1a; step 1&#xff1a;使用栈辅助处理优先级&#xff0c;默认符号为加号。 step 2&#xff1a;遍历字符串&#xff0c;遇到数字&#xff0c;则将连续的数字字符部分转化为int型数字。 step 3&#xff1a;遇到左括号&#xff0c;则将括号后的部分送入递归&#x…

小程序高频面试题

1 请谈谈微信小程序主要目录和文件的作用&#xff1f; project.config.json 项目配置文件&#xff0c;用得最多的就是配置是否开启https校验&#xff1b; App.js 设置一些全局的基础数据等&#xff1b; App.json 底部tab, 标题栏和路由等设置&#xff1b; App.wxss 公…

一个简单的光线追踪渲染器

前言 本文参照自raytracing in one weekend教程&#xff0c;地址为&#xff1a;https://raytracing.github.io/books/RayTracingInOneWeekend.html 什么是光线追踪&#xff1f; 光线追踪模拟现实中的成像原理&#xff0c;通过模拟一条条直线在场景内反射折射&#xff0c;最终…

C++学习笔记01

01.C概述&#xff08;了解&#xff09; c语言在c语言的基础上添加了面向对象编程和泛型编程的支持。 02.第一个程序helloworld&#xff08;掌握&#xff09; #define _CRT_SECURE_NO_WARNINGS #include<iostream> using namespace std;//标准命名空间int main() {//co…