From 5697cdebf4f3d6626d29ed0d99d948e285e339e7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BC=80=E6=BA=90=E6=B5=B7=E5=93=A5?= Date: Wed, 12 Apr 2023 14:22:53 +0800 Subject: [PATCH] fixed: can not create entity instance which with lombok @Data annotation --- .../com/mybatisflex/core/util/ClassUtil.java | 35 +++++++++++++++---- 1 file changed, 29 insertions(+), 6 deletions(-) diff --git a/mybatis-flex-core/src/main/java/com/mybatisflex/core/util/ClassUtil.java b/mybatis-flex-core/src/main/java/com/mybatisflex/core/util/ClassUtil.java index a60bf649..3336f9b3 100644 --- a/mybatis-flex-core/src/main/java/com/mybatisflex/core/util/ClassUtil.java +++ b/mybatis-flex-core/src/main/java/com/mybatisflex/core/util/ClassUtil.java @@ -18,6 +18,7 @@ package com.mybatisflex.core.util; import java.lang.reflect.Constructor; import java.lang.reflect.Field; +import java.lang.reflect.Modifier; import java.lang.reflect.Proxy; import java.util.ArrayList; import java.util.Arrays; @@ -70,13 +71,35 @@ public class ClassUtil { public static T newInstance(Class clazz) { try { - Constructor constructor = clazz.getDeclaredConstructor(); - return constructor.newInstance(); - } catch (Exception e) { - e.printStackTrace(); - } + Constructor defaultConstructor = null; + Constructor otherConstructor = null; - return null; + Constructor[] declaredConstructors = clazz.getDeclaredConstructors(); + for (Constructor constructor : declaredConstructors) { + if (constructor.getParameterCount() == 0) { + defaultConstructor = constructor; + } else if (Modifier.isPublic(constructor.getModifiers())) { + otherConstructor = constructor; + } + } + if (defaultConstructor != null) { + return (T) defaultConstructor.newInstance(); + } else if (otherConstructor != null) { + Class[] parameterTypes = otherConstructor.getParameterTypes(); + Object[] parameters = new Object[parameterTypes.length]; + for (int i = 0; i < parameterTypes.length; i++) { + if (parameterTypes[i].isPrimitive()) { + parameters[i] = ConvertUtil.getPrimitiveDefaultValue(parameterTypes[i]); + } else { + parameters[i] = null; + } + } + return (T) otherConstructor.newInstance(parameters); + } + throw new IllegalArgumentException("the class \"" + clazz.getName() + "\" has no constructor."); + } catch (Exception e) { + throw new RuntimeException("Can not newInstance class: " + clazz.getName()); + } }