增加列表通过类名得到接口实例列表方法

This commit is contained in:
wanggeng 2022-04-01 21:54:00 +08:00
parent 527d533d52
commit 6d156e3d46

View File

@ -1,13 +1,13 @@
package ink.wgink.util;
import org.apache.commons.collections.KeyValue;
import org.apache.commons.collections.keyvalue.DefaultKeyValue;
import org.apache.commons.lang3.StringUtils;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
@ -22,6 +22,35 @@ import java.util.Map;
**/
public class ReflectUtil {
/**
* 获取接口实例实例必须有无参构造方法
*
* @param instanceClassNames 实现类名
* @param interfaceClass 接口
* @param <T>
* @return
* @throws ReflectException
*/
public static <T> List<T> listInterfaceInstance(List<String> instanceClassNames, Class<T> interfaceClass) throws ReflectException {
if (instanceClassNames == null || instanceClassNames.isEmpty()) {
throw new ReflectException("instanceClassNames 不能为空");
}
if (interfaceClass == null) {
throw new ReflectException("interfaceClass 不能为空");
}
List<T> instances = new ArrayList<>();
try {
for (String instanceClassName : instanceClassNames) {
Class clazz = Class.forName(instanceClassName);
T instance = (T) clazz.getConstructor().newInstance();
instances.add(instance);
}
} catch (ClassNotFoundException | InvocationTargetException | InstantiationException | IllegalAccessException | NoSuchMethodException e) {
e.printStackTrace();
}
return instances;
}
/**
* 获取单例对象
*