我习惯于在类型集合中使用泛型,但我从未真正使用过它们来开发某些东西。
我有几个这样的类:
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) {
});
}
}其中,两者之间唯一变化的是服务字符串("/services/info")和列表的类型(本例中为LogInfo)
我已经将几个方法重构为一个GenericWsClient类,但我的目标是拥有一些可以像这样使用的东西:
List<LogInfo> myList = database.getList();
SuperGenericClient<List<LogInfo>> superClient = new SuperGenericClient<List<LogInfo>>();
superClient.send(myList,"/services/logInfo");但我不知道该怎么做,甚至不知道它是否可行。有可能吗?
发布于 2012-05-16 00:02:23
是的,事实上,如果你查看java.util.collection包,你会发现所有的类都是参数find。
所以你的类应该是这样的
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。
发布于 2012-05-16 00:03:07
你可以像下面这样写你的类--你可以将同样的想法应用于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");发布于 2012-05-16 00:03:58
像这样声明你的类:
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);https://stackoverflow.com/questions/10604504
复制相似问题