feat: ClassUtil.newInstance() add create from factory method support

This commit is contained in:
开源海哥 2023-07-30 11:22:53 +08:00
parent b8b2d1bf21
commit 6d50a6228b

View File

@ -138,6 +138,16 @@ public class ClassUtil {
} }
return (T) otherConstructor.newInstance(parameters); return (T) otherConstructor.newInstance(parameters);
} }
// 没有任何构造函数的情况下去查找 static 工厂方法满足 lombok 注解的需求
else {
Method factoryMethod = ClassUtil.getFirstMethod(clazz, m -> m.getParameterCount() == 0
&& clazz.isAssignableFrom(m.getReturnType())
&& Modifier.isPublic(m.getModifiers())
&& Modifier.isStatic(m.getModifiers()));
if (factoryMethod != null) {
return (T) factoryMethod.invoke(null);
}
}
throw new IllegalArgumentException("the class \"" + clazz.getName() + "\" has no constructor."); throw new IllegalArgumentException("the class \"" + clazz.getName() + "\" has no constructor.");
} catch (Exception e) { } catch (Exception e) {
throw new RuntimeException("Can not newInstance class: " + clazz.getName()); throw new RuntimeException("Can not newInstance class: " + clazz.getName());