Table of contents
2. Upgraded version - multi-layer nesting
3. The final version - various collections
1. Basic version
1. Tools
Use the reflection mechanism to realize the default value assignment function of any entity class field
import java.lang.reflect.Field;
public class EntityDefaultValues {
/**
* 为指定实体类的所有字段赋默认值
* @param entityClass 实体类的Class对象
* @param <T> 实体类的类型
* @throws IllegalAccessException 当访问实体类字段失败时抛出
* @throws InstantiationException 当创建实体类实例失败时抛出
*/
public static <T> T setDefaultValues(Class<T> entityClass) throws IllegalAccessException, InstantiationException {
// 使用newInstance方法创建实体类的实例
T entity = entityClass.newInstance();
// 获取实体类的所有字段
Field[] fields = entityClass.getDeclaredFields();
// 遍历所有字段并为其赋默认值
for(Field field : fields){
field.setAccessible(true);
Object value = getDefaultFieldValue(field.getType());
field.set(entity, value);
}
return entity;
}
/**
* 获取指定数据类型的默认值
* @param type 数据类型的Class对象
* @return 数据类型的默认值
*/
private static Object getDefaultFieldValue(Class<?> type) {
if(type == int.class || type == Integer.class){
return 0;
}else if(type == long.class || type == Long.class){
return 0L;
}else if(type == float.class || type == Float.class){
return 0.0F;
}else if(type == double.class || type == Double.class){
return 0.0D;
}else if(type == byte.class || type == Byte.class){
return (byte)0;
}else if(type == short.class || type == Short.class){
return (short)0;
}else if(type == boolean.class || type == Boolean.class){
return false;
}else if(type == char.class || type == Character.class){
return '\u0000';
}else{
return null; // 引用类型默认为null
}
}
}
2. Entity class and test code
Use the EntityDefaultValues tool class to assign default values to all fields of the TestEntity entity class and output the results. It should be noted that getter and setter methods must be added to all fields of the entity class before using this tool class.
public class TestEntity {
int id;
String name;
boolean finished;
// 构造函数省略
// 必须添加getter和setter方法
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isFinished() {
return finished;
}
public void setFinished(boolean finished) {
this.finished = finished;
}
}
// 测试
public class Test {
public static void main(String[] args) throws IllegalAccessException, InstantiationException {
TestEntity entity = EntityDefaultValues.setDefaultValues(TestEntity.class);
System.out.println(entity.getId()); // 输出 0
System.out.println(entity.getName()); // 输出 null
System.out.println(entity.isFinished()); // 输出 false
}
}
2. Upgraded version - multi-layer nesting
An entity contains multiple nested sub-entities, and default values can be assigned to all sub-entities and sub-entity fields in a recursive manner. The following is the expanded tool class code
1. Tools
This tool class code implements the function of assigning default values to all fields of any entity class and all fields of multi-layer sub-entity classes. The method of use is the same as the above example. It should be noted that getter and setter methods must be added to all fields of the entity class before using the tool class. At the same time, when performing recursion, it is necessary to determine whether the type of the child entity class has the ClassLoader attribute, so as to determine whether it is an entity class. If it is an entity class, use a recursive method to assign default values to the fields of the child entity class.
import java.lang.reflect.Field;
public class EntityDefaultValues {
/**
* 为指定实体类的所有字段以及多层子实体类的字段赋默认值
* @param entityClass 实体类的Class对象
* @param <T> 实体类的类型
* @throws IllegalAccessException 当访问实体类字段失败时抛出
* @throws InstantiationException 当创建实体类实例失败时抛出
*/
public static <T> T setDefaultValues(Class<T> entityClass) throws IllegalAccessException, InstantiationException {
// 使用newInstance方法创建实体类的实例
T entity = entityClass.newInstance();
// 获取实体类的所有字段
Field[] fields = entityClass.getDeclaredFields();
// 遍历所有字段并为其赋默认值
for(Field field : fields){
field.setAccessible(true);
// 如果该字段是一个实体类
if(field.getType().getClassLoader() != null){
// 使用递归方式为子实体类的字段赋默认值
Object subEntity = setDefaultValues(field.getType());
field.set(entity, subEntity);
}else{
Object value = getDefaultFieldValue(field.getType());
field.set(entity, value);
}
}
return entity;
}
/**
* 获取指定数据类型的默认值
* @param type 数据类型的Class对象
* @return 数据类型的默认值
*/
private static Object getDefaultFieldValue(Class<?> type) {
if(type == int.class || type == Integer.class){
return 0;
}else if(type == long.class || type == Long.class){
return 0L;
}else if(type == float.class || type == Float.class){
return 0.0F;
}else if(type == double.class || type == Double.class){
return 0.0D;
}else if(type == byte.class || type == Byte.class){
return (byte)0;
}else if(type == short.class || type == Short.class){
return (short)0;
}else if(type == boolean.class || type == Boolean.class){
return false;
}else if(type == char.class || type == Character.class){
return '\u0000';
}else{
return null; // 引用类型默认为null
}
}
}
2. Entity class and test code
Use the EntityDefaultValues tool class to assign default values to all fields of the TestEntity entity class and its internal SubEntity subentity classes. The result outputs the default values of the numeric type, character type, and Boolean type, the date type is null, and the reference type is also null.
public class TestEntity {
int id;
String name;
boolean finished;
Date createTime;
SubEntity subEntity;
// 构造函数省略
// 必须添加getter和setter方法
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isFinished() {
return finished;
}
public void setFinished(boolean finished) {
this.finished = finished;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public SubEntity getSubEntity() {
return subEntity;
}
public void setSubEntity(SubEntity subEntity) {
this.subEntity = subEntity;
}
}
public class SubEntity {
int subId;
String subName;
// 构造函数省略
// 必须添加getter和setter方法
public int getSubId() {
return subId;
}
public void setSubId(int subId) {
this.subId = subId;
}
public String getSubName() {
return subName;
}
public void setSubName(String subName) {
this.subName = subName;
}
}
// 测试
public class Test {
public static void main(String[] args) throws IllegalAccessException, InstantiationException {
TestEntity entity = EntityDefaultValues.setDefaultValues(TestEntity.class);
System.out.println(entity.getId()); // 输出 0
System.out.println(entity.getName()); // 输出 null
System.out.println(entity.isFinished()); // 输出 false
System.out.println(entity.getCreateTime()); // 输出 null
System.out.println(entity.getSubEntity().getSubId()); // 输出 0
System.out.println(entity.getSubEntity().getSubName()); // 输出 null
}
}
3. The final version - various collections
1. Tools
The tool class code implements default values for all fields of any entity class, all fields of multi-layer sub-entity classes, and various types of collection fields. It should be noted that before using this tool class, you must set all fields of the entity class Added getter and setter methods. At the same time, when performing recursion, it is necessary to determine whether the type of the child entity class has the ClassLoader attribute, so as to determine whether it is an entity class. For various types of collection fields, it is necessary to determine the default value and specific implementation class by judging the specific implementation class of the collection. For fields of basic types and reference types, you can use the getDefaultFieldValue() method to obtain their default values.
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class EntityDefaultValues {
/**
* 为指定实体类的所有字段以及多层子实体类的字段、各种集合类型的字段赋默认值
* @param entityClass 实体类的Class对象
* @param <T> 实体类的类型
* @throws IllegalAccessException 当访问实体类字段失败时抛出
* @throws InstantiationException 当创建实体类实例失败时抛出
*/
public static <T> T setDefaultValues(Class<T> entityClass) throws IllegalAccessException, InstantiationException {
// 使用newInstance方法创建实体类的实例
T entity = entityClass.newInstance();
// 获取实体类的所有字段
Field[] fields = entityClass.getDeclaredFields();
// 遍历所有字段并为其赋默认值
for(Field field : fields){
field.setAccessible(true);
Object value = null;
Class<?> fieldType = field.getType();
// 如果该字段是一个集合类型
if(Collection.class.isAssignableFrom(fieldType)){
// 判断集合类型的具体实现类
if(List.class.isAssignableFrom(fieldType)){
// 创建一个空的List对象
value = new ArrayList<>();
}else if(Map.class.isAssignableFrom(fieldType)){
// 创建一个空的HashMap对象
value = new HashMap<>();
}else{
// 其他类型的集合使用空的Collection对象
value = new ArrayList<>();
}
field.set(entity, value);
}
// 如果该字段是一个实体类
else if(fieldType.getClassLoader() != null){
// 使用递归方式为子实体类的字段赋默认值
Object subEntity = setDefaultValues(fieldType);
field.set(entity, subEntity);
}
// 如果该字段是一个基本类型或引用类型
else{
value = getDefaultFieldValue(fieldType);
field.set(entity, value);
}
}
return entity;
}
/**
* 获取指定数据类型的默认值
* @param type 数据类型的Class对象
* @return 数据类型的默认值
*/
private static Object getDefaultFieldValue(Class<?> type) {
if(type == int.class || type == Integer.class){
return 0;
}else if(type == long.class || type == Long.class){
return 0L;
}else if(type == float.class || type == Float.class){
return 0.0F;
}else if(type == double.class || type == Double.class){
return 0.0D;
}else if(type == byte.class || type == Byte.class){
return (byte)0;
}else if(type == short.class || type == Short.class){
return (short)0;
}else if(type == boolean.class || type == Boolean.class){
return false;
}else if(type == char.class || type == Character.class){
return '\u0000';
}else{
return null; // 引用类型默认为null
}
}
}
2. Entity class and test code
Use the EntityDefaultValues tool class to assign default values to all fields of the TestEntity entity class and its internal SubEntity subentity classes. The result outputs the default values of the numeric type, character type, and Boolean type, the date type is null, the reference type is also null, and the List and Map types are the default empty collection objects. It should be noted that when performing recursion, it is necessary to determine whether the type of the child entity class has the ClassLoader attribute, so as to determine whether it is an entity class. If it is an entity class, use a recursive method to assign default values to the fields of the child entity class. At the same time, when assigning default values to fields of List and Map types, it is necessary to determine the default value and the specific implementation class by judging the specific implementation class of the collection.
import java.util.Date;
import java.util.List;
import java.util.Map;
public class TestEntity {
int id;
String name;
boolean finished;
Date createTime;
SubEntity subEntity;
List<SubEntity> subEntityList;
Map<String, SubEntity> subEntityMap;
// 构造函数省略
// 必须添加getter和setter方法
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isFinished() {
return finished;
}
public void setFinished(boolean finished) {
this.finished = finished;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public SubEntity getSubEntity() {
return subEntity;
}
public void setSubEntity(SubEntity subEntity) {
this.subEntity = subEntity;
}
public List<SubEntity> getSubEntityList() {
return subEntityList;
}
public void setSubEntityList(List<SubEntity> subEntityList) {
this.subEntityList = subEntityList;
}
public Map<String, SubEntity> getSubEntityMap() {
return subEntityMap;
}
public void setSubEntityMap(Map<String, SubEntity> subEntityMap) {
this.subEntityMap = subEntityMap;
}
}
public class SubEntity {
int subId;
String subName;
// 构造函数省略
// 必须添加getter和setter方法
public int getSubId() {
return subId;
}
public void setSubId(int subId) {
this.subId = subId;
}
public String getSubName() {
return subName;
}
public void setSubName(String subName) {
this.subName = subName;
}
}
// 测试
public class Test {
public static void main(String[] args) throws IllegalAccessException, InstantiationException {
TestEntity entity = EntityDefaultValues.setDefaultValues(TestEntity.class);
System.out.println(entity.getId()); // 输出 0
System.out.println(entity.getName()); // 输出 null
System.out.println(entity.isFinished()); // 输出 false
System.out.println(entity.getCreateTime()); // 输出 null
System.out.println(entity.getSubEntity().getSubId()); // 输出 0
System.out.println(entity.getSubEntity().getSubName()); // 输出 null
System.out.println(entity.getSubEntityList()); // 输出 []
System.out.println(entity.getSubEntityMap()); // 输出 {}
}
}
Please like it if it is useful, and develop a good habit!
Please leave a message for questions, exchanges, and encouragement!