我对Java泛型非常陌生,已经花费了大量时间寻找适当的解决方案(如果有的话)。
我正在尝试设计适配器来处理特定类型的类对象。如下所述,CAdapter类仅处理"CClass"对象。我正在尝试提供一个抽象的通用适配器,它处理大部分工作(就像Java集合LinkedList一样)。然后为需要支持的每种类型提供具体的适配器实现。
// Classes
public interface AInterface {
public String toString();
}
public class BClass extends AInterface {
public String toString() { return "BClass "; }
}
public class CClass extends AInterface {
public String toString() { return "CClass"; }
}
// Adapters
public interface AdapterInterface<T extends AInterface> {
public T getInterface();
}
public class BAdapter implements AdapterInterface<BClass> {
private BClass aInterface = null;
public BClass getInterface() { return aInterface; }
}
public class CAdapter implements AdapterInterface<CClass> {
private CClass aInterface = null;
public CClass getInterface() { return aInterface; }
}
首先,我看到有人说提供一个具体实现的通用适配器是被嫌弃的(好像会导致上帝打死一只小猫)。也许有人能进一步解释一下这个情况?
其次,我遇到了一个问题,就是动态实例化适配器时没有让Java编译器发出警告。例如,我有一个方法:
public <T extends AInterface> AdapterInterface<T> getAdapter(String type) {
AdapterInterface<T> result = null;
if (type.equals("C") {
result = new CAdapter();
}
return result;
}
当然,编译器会抱怨CAdapter与之不匹配。对于任何类型的AInterface对象,我想能够加载正确的适配器并适当地处理它。我无法理解工厂模式以实现这一点。如有任何想法,请不吝赐教。
<T> T getWhateverOfType(Class<T> type)
时,类型标记很有用,因为涉及到Class.newInstance()
、Class.cast()
等。如果您不处理给定类的实例,则它们是没有用处的。 - millimooseAdapterInterface
的代码时,我首先会在浏览器中打开Langer的泛型FAQ。 - gnat