实现通过子类名称字符串 动态获取生成子类.
用于模板方法, 抽象工厂模式等.
代码实现:
public TheParentClass getSubClass(String subClassName) { Class<?> classSub = Class.forName(subClassName); TheParentClass newClass = classSub.asSubclass(TheParentClass.class).newInstance(); // newClass.doMethod(); return newClass; }
用于代替以下逻辑实现:
public TheParentClass getSubClass(String subClassName) { if(subClassName=="SubClassA"); { return new SubClassA(); } else if(subClassName=="SubClassB"); { return new SubClassB(); } //...... else { return null; } }