假设我们有:
abstract class Item { public Item(){}}
abstract class ExtraItem extends Item { public ExtraItem(){}}
class A extends Item{ public A(){}}
class B extends Item{ public B(){}}
class C extends Item{ public C(){}}
class EA extends ExtraItem{ public A(){}}
class EB extends ExtraItem{ public B(){}}
class EC extends ExtraItem{ public C(){}}
我想写这样的工厂类但没有强制转换:
class Factory {
Item createItem(String className){
Class clazz = Class.forName(className);
return (Item) clazz.newInstance(); //I don't want here cast to Item
}
ExtraItem createExtraItem(String className){
Class<? extends ExtraItem> clazz = (Class<? extends ExtraItem>) Class.forName(className); // I don't want here cast to Extraitem
return clazz.newInstance();
}
}
我试着像上面那样写(当然有演员表):
@SuppressWarnings("unchecked")
public static <T extends Item> T createItem(String protocolType) {
try {
String className = protocolType;
Class<?> clazz = Class.forName(className);
return (T) clazz.newInstance();
} catch (Exception e) {
Log.e("ItemFactory", "Lack key \"" + protocolType + "\" in map: " + e.getLocalizedMessage());
}
return null;
}
但是如何在这里使用 Class.cast() 方法?这是更好的方法吗?