2012-05-15 43 views
2

我習慣在類型化集合中使用泛型,但我從來沒有真正使用它們來開發一些東西。使用泛型進行重構

我有幾類這樣的:

public class LogInfoWsClient extends GenericWsClient { 
    public void sendLogInfo(List<LogInfo> logInfoList) { 
     WebResource ws = super.getWebResource("/services/logInfo"); 
     try { 
      String response = ws.accept(MediaType.TEXT_HTML).type(MediaType.APPLICATION_XML).put(String.class, new GenericEntity<List<LogInfo>>(logInfoList) { 
      });  
    } 
} 

其中一個和另一個之間改變的唯一的事情是服務字符串(「/服務/信息」),並且列表LOGINFO(在這種類型情況)

我已經重構了幾個方法到GenericWsClient類,但我的目標是有什麼東西我可以用這樣的:

List<LogInfo> myList = database.getList(); 
SuperGenericClient<List<LogInfo>> superClient = new SuperGenericClient<List<LogInfo>>(); 
superClient.send(myList,"/services/logInfo"); 

但我不能無花果如何做到這一點,或者即使有可能。可能嗎?

回答

1

是的,如果你看看java.util.collection包,你可以發現所有的類都是parameterzid。

所以你的類將是這樣的

public SuperGenericClient<E> {  
    public E getSomething() { 
     return E; 
    } 
} 

然後使用它,你將有

SuperGenericClient<String> myGenericClient = new SuperGenericClient<String>(); 
String something = myGenericClient.getSomething(); 

擴展你本身例如你的代碼看起來就像這樣:

public class SuperGenericClient<E> extends GenericWsClient { 
    public void send(List<E> entityList, String service) { 
     WebResource ws = super.getWebResource(service); 
     try { 
      String response = ws.accept(MediaType.TEXT_HTML).type(MediaType.APPLICATION_XML).put(String.class, new GenericEntity<E>(entityList) { 
      }); 
     }    
    } 
} 

public class GenericEntity<E> { 
    public GenericEntity(List<E> list){ 

    } 
} 

您必須閱讀this才能非常瞭解泛型。

1

你可以像下面這樣寫你的班級 - 你可以將相同的想法應用到GenericEntity

public class SuperGenericClient<T> extends GenericWsClient { 

    public void send(List<T> list, String service) { 
     WebResource ws = super.getWebResource(service); 
     try { 
      String response = ws.accept(MediaType.TEXT_HTML).type(MediaType.APPLICATION_XML).put(String.class, new GenericEntity<T>(list) { 
      }); 
     }    
    } 
} 

然後,您可以調用它像:

List<LogInfo> myList = database.getList(); 
SuperGenericClient<LogInfo> superClient = new SuperGenericClient<LogInfo>(); 
superClient.send(myList,"/services/logInfo"); 
1

聲明你的類是這樣的:

public class LogThing<T> { 
    public void sendLogInfo(List<T> list) { 
     // do thing! 
    } 
} 

而當你使用它,這樣做是這樣的:

List<LogInfo> myList = db.getList(); 
LogThing<LogInfo> superClient = new LogThing<LogInfo>(); 
superClient.sendLogInfo(myList);