實現通過子類名稱字符串 動態獲取生成子類.
用於模板方法, 抽象工廠模式等.
代碼實現:
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; } }