我的问题与将泛型引入遗留 Java 类有关。下面代码中我想要生成的遗留类是 ClientObjectProxy 和 ClientObjectContainer。ClientObject 保持不变。为简单起见,我将所有类放在一个外部类中。
现在,在旧代码中,对未参数化的 ClientObjectProxyContainer 实例有许多方法 ClientObjectProxyContainer.getProxies() 调用。
通过引入泛型,循环 4 中的现有代码将不再编译,需要将调用提取到循环 1 中的局部变量,或者需要使用带问号的声明,类似于循环 2。新代码应使用参数化循环 3 中的变量。
我的问题是,这是适合我的方法,将现有代码更改为循环 1 或循环 2,还是有不修改遗留代码的方法?
谢谢
简
import java.util.ArrayList;
import java.util.List;
public class GenericForumsExample {
/**
* This class is unchanged
*/
private class ClientObject {
}
/**
* @param <T> Type of the ClientObject behind this proxy
*/
private class ClientObjectProxy<T extends ClientObject> {
}
/**
* @param <T> Type of the ClientObject contained in this collection
*/
private class ClientObjectProxyContainer<T extends ClientObject> {
//Previous signature was:
// public List<ClientObjectProxy> getProxies(){
// New signature is the following
public List<ClientObjectProxy<T>> getProxies(){
return new ArrayList<ClientObjectProxy<T>>();
}
}
public void testScenario() {
ClientObjectProxyContainer proxyContainer = new ClientObjectProxyContainer();
List<ClientObjectProxy> proxies = proxyContainer.getProxies(); // Just a compiler warning
// Loop 1
for (ClientObjectProxy proxy : proxies) { // Compiler OK
//Do something...
}
// Loop 2
ClientObjectProxyContainer<?> clientObjectProxyContainer = new ClientObjectProxyContainer();
for (ClientObjectProxy<?> proxy : clientObjectProxyContainer.getProxies()) {
//Do something...
}
// Loop 3
for (ClientObjectProxy<ClientObject> proxy : new ClientObjectProxyContainer<ClientObject>().getProxies()) {
//Do something...
}
// Loop 4
// Compiler fails on next code line
// incompatible types
// found : java.lang.Object
// required: GenericForumsExample.ClientObjectProxy
for (ClientObjectProxy proxy : proxyContainer.getProxies()) {
//Do something...
}
}
}