当前位置:网站首页>[Commons beanautils topic] 005- convertutils topic
[Commons beanautils topic] 005- convertutils topic
2022-07-24 11:50:00 【Zibo Zibo】
【commons-beanutils project 】005- ConvertUtils project
List of articles
One 、 Get ready
0、ConvertUtils The main role
Mainly used for type conversion , Customizable converter !
1、 introduce commons-beanutils rely on
<!-- Introduce dependencies commons-beanutils-->
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.9.4</version>
</dependency>
2、pom.xml file
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.1</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.zibo</groupId>
<artifactId>zibo2022</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>zibo2022</name>
<description>zibo2022</description>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- Introduce dependencies commons-beanutils-->
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.9.4</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.7.1</version>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
3、 Entity class
Cat
package com.zibo.zibo2022.convert_utils.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Cat {
private String name;
private Integer age;
}
CatDto
package com.zibo.zibo2022.convert_utils.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/** * @author zibo * @date 2022/7/20 0020 18:56 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class CatDto {
private String name;
private Integer age;
}
4、 Custom converter
package com.zibo.zibo2022.convert_utils.converter;
import com.zibo.zibo2022.convert_utils.entity.Cat;
import com.zibo.zibo2022.convert_utils.entity.CatDto;
import java.lang.reflect.InvocationTargetException;
import org.apache.commons.beanutils.Converter;
import org.apache.commons.beanutils.PropertyUtils;
/** * Here simply write a converter , Is used to Cat Object to CatDto object * * @author zibo * @date 2022/7/20 0020 19:00 */
public class CatConverter implements Converter {
@Override
public <T> T convert(Class<T> type, Object value) {
try {
if (!(value instanceof Cat)) {
throw new IllegalArgumentException(" Wrong parameter type !");
}
if (type != CatDto.class) {
throw new IllegalArgumentException(" Wrong parameter type !");
}
String name = (String) PropertyUtils.getProperty(value, "name");
Integer age = (Integer) PropertyUtils.getProperty(value, "age");
T newInstance = type.getDeclaredConstructor().newInstance();
PropertyUtils.setProperty(newInstance, "name", name);
PropertyUtils.setProperty(newInstance, "age", age);
return newInstance;
} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException | InstantiationException e) {
throw new RuntimeException(e);
}
}
}
5、 Pre code
Cat cat = new Cat(" kitten ", 1);
Cat cat2 = new Cat(" kitten 2", 2);
Two 、 Type conversion
1、 Convert objects to strings
// 1、 Convert objects to strings
String convert = ConvertUtils.convert(cat);
System.out.println(convert); // Cat(name= kitten , age=1)
// The following is noteworthy , If it's an array , Convert only the first element
String convert20 = ConvertUtils.convert(new Cat[] {
cat, cat2});
System.out.println(convert20); // Cat(name= kitten , age=1)
String convert40 = ConvertUtils.convert(new String[] {
" kitten ", "1", " Casually written content "});
System.out.println(convert40);
String convert10 = ConvertUtils.convert(new Long[] {
1L, 2L, 3L});
System.out.println(convert10); // 1
2、 Converts a string to an object of the specified data type
// 2、 Converts a string to an object of the specified data type
String one = "1";
Integer convert1 = (Integer) ConvertUtils.convert(one, Integer.class);
System.out.println(convert1); // 1
Object convert2 = ConvertUtils.convert(one, Boolean.class);
System.out.println(convert2); // true
Object convert4 = ConvertUtils.convert("true", Boolean.class);
System.out.println(convert4); // true
Integer[] convert5 = (Integer[]) ConvertUtils.convert("[1, 2, 3]", Integer[].class);
for (Integer integer : convert5) {
System.out.println(integer);
}
// 1
// 2
// 3
// The following cannot be converted !!!
// Cat convert6 = (Cat)ConvertUtils.convert("Cat(name= kitten , age=1)", Cat.class);
// System.out.println(convert6);
// org.apache.commons.beanutils.ConversionException: Default conversion to com.zibo.zibo2022.convert_utils.entity.Cat failed.
3、 Converts an array of specified values to an array of objects of the specified class ( If possible )
// 3、 Converts an array of specified values to an array of objects of the specified class ( If possible )
String[] array = {
" Eating rats ", " Eat fish "};
String[] convert3 = (String[]) ConvertUtils.convert(array, String.class);
System.out.println(Arrays.toString(convert3)); // [ Eating rats , Eat fish ]
String[] arr = {
"true", "false"};
Boolean[] conver4 = (Boolean[]) ConvertUtils.convert(arr, Boolean.class);
System.out.println(Arrays.toString(conver4)); // [true, false]
4、 Converts an object to an object of the specified data type
// 4、 Converts an object to an object of the specified data type
Boolean convert7 = (Boolean) ConvertUtils.convert("true", Boolean.class);
System.out.println(convert7); // true
5、 Convert basic type to wrapper class
// 10、 Convert basic type to wrapper class
int i = 1;
Integer i2 = (Integer) ConvertUtils.convert(i, Integer.class);
System.out.println(i2); // 1
3、 ... and 、 converter
1、 Register custom converter
See the preparation section for the converter !
// 5、 Register converter
// Here is the custom converter , Then register
ConvertUtils.register(new CatConverter(), Cat.class);
CatConverter catConverter = new CatConverter();
CatDto catDto = catConverter.convert(CatDto.class, cat);
System.out.println(catDto); // CatDto(name= kitten , age=1)
2、 Find a converter of the specified type
// 6、 Find a converter of the specified type
Converter lookup = ConvertUtils.lookup(Cat.class);
System.out.println(lookup); // [email protected]
3、 Find a converter that converts a specified type to another type
// 7、 Find a converter that converts a specified type to another type
Converter lookup2 = ConvertUtils.lookup(String.class, Boolean.class);
System.out.println(lookup2); // ConverterFacade[BooleanConverter[UseDefault=true]]
Converter converter = ConvertUtils.lookup(CatDto.class, Cat.class);
System.out.println(converter); // [email protected]
// Pay attention to the following
Converter lookup3 = ConvertUtils.lookup(Cat.class, CatDto.class);
System.out.println(lookup3); // null
4、 Remove the converter of the specified type
// 8、 Remove the converter of the specified type
ConvertUtils.deregister(Cat.class);
Converter converter1 = ConvertUtils.lookup(CatDto.class, Cat.class);
System.out.println(converter1); // null
5、 Remove all registered converters
// 9、 Remove all registered converters
ConvertUtils.deregister();
Four 、 Complete code
package com.zibo.zibo2022.convert_utils.main;
import com.zibo.zibo2022.convert_utils.converter.CatConverter;
import com.zibo.zibo2022.convert_utils.entity.Cat;
import com.zibo.zibo2022.convert_utils.entity.CatDto;
import java.util.Arrays;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.Converter;
public class Main {
public static void main(String[] args) {
Cat cat = new Cat(" kitten ", 1);
Cat cat2 = new Cat(" kitten 2", 2);
// 1、 Convert objects to strings
String convert = ConvertUtils.convert(cat);
System.out.println(convert); // Cat(name= kitten , age=1)
// The following is noteworthy , If it's an array , Convert only the first element
String convert20 = ConvertUtils.convert(new Cat[] {
cat, cat2});
System.out.println(convert20); // Cat(name= kitten , age=1)
String convert40 = ConvertUtils.convert(new String[] {
" kitten ", "1", " Casually written content "});
System.out.println(convert40);
String convert10 = ConvertUtils.convert(new Long[] {
1L, 2L, 3L});
System.out.println(convert10); // 1
// 2、 Converts a string to an object of the specified data type
String one = "1";
Integer convert1 = (Integer) ConvertUtils.convert(one, Integer.class);
System.out.println(convert1); // 1
Object convert2 = ConvertUtils.convert(one, Boolean.class);
System.out.println(convert2); // true
Object convert4 = ConvertUtils.convert("true", Boolean.class);
System.out.println(convert4); // true
Integer[] convert5 = (Integer[]) ConvertUtils.convert("[1, 2, 3]", Integer[].class);
for (Integer integer : convert5) {
System.out.println(integer);
}
// 1
// 2
// 3
// The following cannot be converted !!!
// Cat convert6 = (Cat)ConvertUtils.convert("Cat(name= kitten , age=1)", Cat.class);
// System.out.println(convert6);
// org.apache.commons.beanutils.ConversionException: Default conversion to com.zibo.zibo2022.convert_utils.entity.Cat failed.
// 3、 Converts an array of specified values to an array of objects of the specified class ( If possible )
String[] array = {
" Eating rats ", " Eat fish "};
String[] convert3 = (String[]) ConvertUtils.convert(array, String.class);
System.out.println(Arrays.toString(convert3)); // [ Eating rats , Eat fish ]
String[] arr = {
"true", "false"};
Boolean[] conver4 = (Boolean[]) ConvertUtils.convert(arr, Boolean.class);
System.out.println(Arrays.toString(conver4)); // [true, false]
// 4、 Converts an object to an object of the specified data type
Boolean convert7 = (Boolean) ConvertUtils.convert("true", Boolean.class);
System.out.println(convert7); // true
// 5、 Register converter
// Here is the custom converter , Then register
ConvertUtils.register(new CatConverter(), Cat.class);
CatConverter catConverter = new CatConverter();
CatDto catDto = catConverter.convert(CatDto.class, cat);
System.out.println(catDto); // CatDto(name= kitten , age=1)
// 6、 Find a converter of the specified type
Converter lookup = ConvertUtils.lookup(Cat.class);
System.out.println(lookup); // [email protected]
// 7、 Find a converter that converts a specified type to another type
Converter lookup2 = ConvertUtils.lookup(String.class, Boolean.class);
System.out.println(lookup2); // ConverterFacade[BooleanConverter[UseDefault=true]]
Converter converter = ConvertUtils.lookup(CatDto.class, Cat.class);
System.out.println(converter); // [email protected]
// Pay attention to the following
Converter lookup3 = ConvertUtils.lookup(Cat.class, CatDto.class);
System.out.println(lookup3); // null
// 8、 Remove the converter of the specified type
ConvertUtils.deregister(Cat.class);
Converter converter1 = ConvertUtils.lookup(CatDto.class, Cat.class);
System.out.println(converter1); // null
// 9、 Remove all registered converters
ConvertUtils.deregister();
// 10、 Convert basic type to wrapper class
int i = 1;
Integer i2 = (Integer) ConvertUtils.convert(i, Integer.class);
System.out.println(i2); // 1
}
}
边栏推荐
- How to choose sentinel vs. hystrix current limiting?
- The art of management - driving software R & D efficiency through leadership
- gcc -l参数和-L参数的区别
- MOS管 —— 快速复苏应用笔记(壹)[原理篇]
- Source code analysis sentry user behavior record implementation process
- Is there any charge for PDF processing? impossible!
- CCF 1-2 question answering record (1)
- 20000 words detailed explanation, thoroughly understand es!
- MySQL advanced (XVII) cannot connect to database server problem analysis
- HCIP OSPF接口网络类型实验 第四天
猜你喜欢

使用Prometheus+Grafana实时监控服务器性能
![MOS管 —— 快速复苏应用笔记(壹)[原理篇]](/img/a1/8427c9b1d0ea0cecce820816510045.png)
MOS管 —— 快速复苏应用笔记(壹)[原理篇]

Linked list - Sword finger offer interview question 02.07. linked list intersection

Three small knowledge points about data product managers

NFT digital collection system construction - app development

字符串——344.反转字符串

1184. 公交站间的距离 : 简单模拟题
![Operational amplifier - Notes on rapid recovery [II] (application)](/img/fd/e12f43e23e6ec76c2b44ce7813e204.png)
Operational amplifier - Notes on rapid recovery [II] (application)
![[deserialization vulnerability-01] Introduction to serialization and deserialization](/img/e4/6b9ee6ee74f3cdc3c886ed3af9ef73.png)
[deserialization vulnerability-01] Introduction to serialization and deserialization

GCC的基本用法
随机推荐
Mysql database
The difference between synchronized and lock locks
L1-064 估值一亿的AI核心代码
【C和指针第14章】预处理器
String -- 344. Reverse string
【Markdown语法高级】让你的博客更精彩(四:设置字体样式以及颜色对照表)
Detailed OSPF configuration of layer 3 switch / router [Huawei ENSP experiment]
Markdown mathematical formula syntax
Leetcode 112. path sum
L1-049 seat allocation of ladder race
Shell script
Three small knowledge points about data product managers
4*4图片权重的收敛规则
【C和指针第11章】动态内存分配
哈希——242.有效的字母异位词
Chapter 1 Introduction
Install JMeter
Easy to understand ES6 (IV): template string
Semaphore详解
MySQL advanced (XVII) cannot connect to database server problem analysis