首发于Enaium的个人博客
新建2个类
public class Test1 {
}
public class Test2 {
public void render() {
System.out.println("Test2");
}
}
public class ClassContainer {
private final HashMap<Class<?>, Object> classes = new HashMap<>();
public ClassContainer() {
List<Class<?>> scanClasses = new ArrayList<>(List.of(Test1.class));//被扫描到的类 上个文章介绍了如何遍历类路径所有类
scanClasses.forEach(it -> {
try {
classes.put(it, it.getConstructor().newInstance());//创建对象 直接newInstance的方法被弃用 所以需要获取无参构造方法再创建对象
} catch (InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
e.printStackTrace();
}
});
}
public <T> T create(Class<T> klass, Object instance) {
classes.put(klass, instance);
return (T) classes.get(klass);
}
public <T> T create(Class<T> klass) {
if (classes.get(klass) == null) {
//如果这类没对象的话就创建
try {
classes.put(klass, klass.getConstructor().newInstance());
} catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
e.printStackTrace();
}
}
return (T) classes.get(klass);//返回对象
}
public HashMap<Class<?>, Object> getClasses() {
return classes;
}
}
测试一下
public class Main {
private static final ClassContainer classContainer = new ClassContainer();
public static void main(String[] args) {
System.out.println(classContainer.create(Test2.class));//第一次创建
System.out.println(classContainer.create(Test2.class));//第二次创建和第一次创建对象相同
System.out.println(classContainer.create(Test2.class, new Test2()));//容器内的类被重新创建
for (Map.Entry<Class<?>, Object> classObjectEntry : classContainer.getClasses().entrySet()) {
System.out.println(classObjectEntry.getKey());//遍历容器内的类
}
}
}