今天分享给大家一个实用的开发技巧, 创建一个返回值为泛型的对象构建函数, 要求是传入返回值类的 class 对象.

例如: 平时我们开发接口的时候发现很多响应类里面基本都会有`code`和`error`两个属性, 而且有的人会将常量的枚举值作为接口调用成功的返回值, 这时候每次都会在接口的末尾处 new 一个接口响应值返回给调用者, 而这时候我们可以统一将这个创建含有成功响应值对象封装为一个方法.

为了节省更多重复代码, 我们会将封装这个方法定义在一个父类中.

​ 父类代码改造前代码:

/**
* @Title: BaseResponse
* @Description:
* @author: deWei
* @date: 2022/3/12 18:28
* @Version: 1.0
*/
@Data
@NoArgsConstructor
public class BaseResponse implements Serializable { <p style="text-indent:2em"/>private static final long serialVersionUID = -8383361046902228836L; <p style="text-indent:2em"/>protected String code;
<p style="text-indent:2em"/>protected String errorMsg; }

思路: ①由于我们不能创建一个对象传入而返回, 这样就无法达到我们减少代码量的需求了, 所以就要用到 java 的反射机制去构建对象, 最后得到参数为 class 对象. ②既然是在父类中定义, 那构建的对象必须就是它的子类, 这时候就需要用到泛型去限制了.

ok, 整理好思路了就开始改造父类了.

父类代码改造后代码 :

/**
* @Title: BaseResponse
* @Description:
* @author: deWei
* @date: 2022/3/12 18:28
* @Version: 1.0
*/
@Data
@NoArgsConstructor
public class BaseResponse implements Serializable { <p style="text-indent:2em"/>private static final long serialVersionUID = -8383361046902228836L; <p style="text-indent:2em"/>protected String code;
<p style="text-indent:2em"/>protected String errorMsg; <p style="text-indent:2em"/>public static <T extends BaseResponse> T setResult(Class<T> tClass, ResponseEnum responseEnum) throws Exception {
<p style="text-indent:2em"/><p style="text-indent:2em"/>Constructor<T> constructor = tClass.getConstructor(ResponseEnum.class);
<p style="text-indent:2em"/><p style="text-indent:2em"/>return constructor.newInstance(responseEnum);
<p style="text-indent:2em"/>} <p style="text-indent:2em"/>/**
<p style="text-indent:2em"/> * 调用的子类需要重写父类的 BaseResponse(ResponseEnum responseEnum) 构造器
<p style="text-indent:2em"/> */
<p style="text-indent:2em"/>public static <T extends BaseResponse> T success(Class<T> tClass) {
<p style="text-indent:2em"/><p style="text-indent:2em"/>try {
<p style="text-indent:2em"/><p style="text-indent:2em"/><p style="text-indent:2em"/>return setResult(tClass, ResponseEnum.NORMAL_SUCCESS);
<p style="text-indent:2em"/><p style="text-indent:2em"/>} catch (Exception e) {
<p style="text-indent:2em"/><p style="text-indent:2em"/><p style="text-indent:2em"/>e.printStackTrace();
<p style="text-indent:2em"/><p style="text-indent:2em"/>}
<p style="text-indent:2em"/><p style="text-indent:2em"/>return null;
<p style="text-indent:2em"/>} <p style="text-indent:2em"/>public static <T extends BaseResponse> T failure(Class<T> tClass) {
<p style="text-indent:2em"/><p style="text-indent:2em"/>try {
<p style="text-indent:2em"/><p style="text-indent:2em"/><p style="text-indent:2em"/>return setResult(tClass, ResponseEnum.SYSTEM_ERROR);
<p style="text-indent:2em"/><p style="text-indent:2em"/>} catch (Exception e) {
<p style="text-indent:2em"/><p style="text-indent:2em"/><p style="text-indent:2em"/>e.printStackTrace();
<p style="text-indent:2em"/><p style="text-indent:2em"/>}
<p style="text-indent:2em"/><p style="text-indent:2em"/>return null;
<p style="text-indent:2em"/>} <p style="text-indent:2em"/>public BaseResponse(ResponseEnum responseEnum) {
<p style="text-indent:2em"/><p style="text-indent:2em"/>this.code = responseEnum.code();
<p style="text-indent:2em"/><p style="text-indent:2em"/>this.errorMsg = responseEnum.errorMsg();
<p style="text-indent:2em"/>} }

响应枚举 ResponseEnum.java:

/**
* @Title: ResponseEnum
* @Description: 响应类实体
* @author: deWei
* @date: 2022/3/12 18:28
* @Version: 1.0
*/
public enum ResponseEnum { <p style="text-indent:2em"/>NORMAL_SUCCESS("000000", "成功"),
<p style="text-indent:2em"/>SYSTEM_ERROR("000001", "系统异常"); <p style="text-indent:2em"/>private final String code;
<p style="text-indent:2em"/>private final String errorMsg; <p style="text-indent:2em"/>ResponseEnum(String code, String errorMsg) {
<p style="text-indent:2em"/><p style="text-indent:2em"/>this.code = code;
<p style="text-indent:2em"/><p style="text-indent:2em"/>this.errorMsg = errorMsg;
<p style="text-indent:2em"/>} <p style="text-indent:2em"/>public String code() {
<p style="text-indent:2em"/><p style="text-indent:2em"/>return code;
<p style="text-indent:2em"/>} <p style="text-indent:2em"/>public String errorMsg() {
<p style="text-indent:2em"/><p style="text-indent:2em"/>return errorMsg;
<p style="text-indent:2em"/>}
}

给定class对象返回该类的实例的更多相关文章

  1. Java中反射机制和Class.forName、实例对象.class(属性)、实例对象getClass()的区别

    一.Java的反射机制   每个Java程序执行前都必须经过编译.加载.连接.和初始化这几个阶段,后三个阶段如下图:   其中

  2. C#利用反射,遍历获得一个类的所有属性名,以及该类的实例的所有属性的值

    转自goldeneyezhang原文 C#利用反射,遍历获得一个类的所有属性名,以及该类的实例的所有属性的值 C#利用反射,遍历获得一个类的所有属性名,以及该类的实例的所有属性的值总结: 对应某个类的 ...

  3. 本文使用springMVC和ajax,实现将JSON对象返回到页面

    一.引言 本文使用springMVC和ajax做的一个小小的demo,实现将JSON对象返回到页面,没有什么技术含量,纯粹是因为最近项目中引入了springMVC框架. 二.入门例子 ①. 建立工程, ...

  4. C++11用于计算函数对象返回类型的统一方法

    [C++11用于计算函数对象返回类型的统一方法] 模板 std::result_of 被TR1 引进且被 C++11 所采纳,可允许我们决定和使用一个仿函数其回返值的类别.底下,CalculusVer ...

  5. JavaScript中创建字典对象(dictionary)实例

    这篇文章主要介绍了JavaScript中创建字典对象(dictionary)实例,本文直接给出了实现的源码,并给出了使用示例,需要的朋友可以参考下 对于JavaScript来说,其自身的Array对象 ...

  6. php xml格式对象 返回->对应格式数组

    /*     * $objXml xml格式对象      * 返回 : 对应格式数组     */    public function XmlString2Arr($xml)    {       ...

  7. easyUIDataGrid对象返回值

    import java.util.List; /** * easyUIDataGrid对象返回值 * <p>Title: EasyUIResult</p> * <p> ...

  8. JS window对象 返回前一个浏览的页面 back()方法

    JS window对象 返回前一个浏览的页面 back()方法,加载 history 列表中的前一个 URL. 语法: window.history.back();   返回前一个浏览的页面 back ...

  9. valueOf()对象返回值

    valueOf()对象返回值 Array数组的元素被转换为字符串,这些字符串由逗号分隔,连接在一起.其操作与 Array.toString 和 Array.join 方法相同. Boolean为Boo ...

随机推荐

  1. 关于final关键字

    final修饰基本数据类型时 修饰的变量值不可变 final修饰引用数据类型时 修饰的变量地址不可变 值可变 final修饰一个类中的方法时 不可被子类重写 final修饰一个类时 不可被其他类继承 ...

  2. LVS负载均衡群集部署——DR模式

    LVS负载均衡群集部署--DR模式 1.LVS-DR概述 2.部署实验 1.LVS-DR概述: LVS-DR(Linux Virtual Server Director Server)工作模式,是生产 ...

  3. PyTorch深度学习入门笔记(一)PyTorch环境配置及安装

    @ 目录 一.工具安装 1.1 Anaconda 安装 1.2 Pytorch安装 二.编辑器安装 2.1 Pycharm安装 2.2 Jupyter安装 OS: ubuntu 20.04(虚拟机) ...

  4. 2、Linux基础--常用系统命令与快捷键

    笔记 1.昨日问题 1.mac系统虚拟机的问题 2.虚拟机连不上网 1.xshell连接不上 1.虚拟网络编辑器和vmnat8网卡设置错误 2.ping不通百度 1.DNS IP编写错误 2.网卡的网 ...

  5. Centos下Ambari2.7.5的编译和安装

    前言 终于,要开始写点大数据相关的文章了.当真的要开始写老本行的时候,还是考虑了挺久的.一是不知道从何处写起,二是如何能写点有意思的. 我们常说,过程比结果重要.也是有很多人喜欢准备完全之后,才会开始 ...

  6. JVM学习——内存空间(学习过程)

    JVM--内存空间 关于内存的内容,内存的划分.JVM1.7 -> 1.8的变化比较大 JVM指令执行的时候,是基于栈的操作.每一个方法执行的时候,都会有一个属于自己的栈帧的数据结构.栈的深度, ...

  7. [LeetCode]1342. 将数字变成 0 的操作次数

    给你一个非负整数 num ,请你返回将它变成 0 所需要的步数. 如果当前数字是偶数,你需要把它除以 2 :否则,减去 1 . 示例 1: 输入:num = 14 输出:6 解释: 步骤 1) 14 ...

  8. selenium+python 处理只读日期控件的2种方法

    前言 有时候测试过程中会遇到日期控件场景,这时候需要特殊处理,下文以12306网站为例 1.处理方式 通常是通过js去除只读属性(2种方法),然后通过send_keys重新写值 from time i ...

  9. 【外企测试面试、笔试】分享下历时8轮、30k+的外企面试全过程

    外企福利 薪酬体系完善(期权.股票等),定期薪酬市场调研,紧跟一线互联网大厂 加班很少很少 年假多,15-20天 国外免费旅游.旅游金 免费培训英语(还可能出国培训) 定期技术交流 免费零食 定期团建 ...

  10. eBPF会成为服务网格的未来吗?

    服务网格现状 服务网格为服务提供了复杂的应用层网络管理,如服务发现.流量路由.弹性(超时/重试/断路).认证/授权.可观察性(日志/度量/追踪)等. 在分布式应用的早期,这些要求是通过直接将所需的逻辑 ...