参数化类型的快捷方式?

我正在使用需要生成大量代码的代码,List<Map<String,Object>>并且必须一直输入例如代码是很笨拙bob = new List<Map<String,Object>>的。

我试图创建一个空类

class ListMap extends List<Map<String,Object>> {}

但是随后的方法List<Map<String,Object>>不接受 a作为它们的类型,如果我将它们分配给 a new ListMap(),我会从返回的方法中得到错误。基本上,我希望 Java 将我的 ListMap 视为与 List> 相同...因为理论上至少通过继承。List<Map<String,Object>>ListMap


牧羊人nacy
浏览 82回答 2
2回答

慕桂英4014372

在这种情况下,最好的做法是为您ListMap的往返添加转换方法List<Map<String, Object>>......知道如果您可以保留对它的引用并通过委托或将更改分开,在这种情况下,您可以共同扩展.ListMapListListMapListMapListjava.util.*class ListMap extends AbstractList<Map<String, Object>> {&nbsp; &nbsp;public ListMap(final Map<String, Object> list) { super(list); }&nbsp;&nbsp; &nbsp;// or&nbsp; &nbsp;public static ListMap fromList(final List<Map<String, Object>> list) {&nbsp; &nbsp; &nbsp; &nbsp;if (list instanceof ListMap) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return (ListMap) list;&nbsp; &nbsp; &nbsp; &nbsp;} else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return new ListMap(list);&nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp;}&nbsp;}如果提供的列表实际上是一个ListMap.

繁星点点滴滴

由于您有方法返回List<Map<String,Object>>,但想将其分配给类型的变量ListMap,并且List<Map<String,Object>>可能实现为 a ArrayList<Map<String,Object>>,因此您不能使其直接与 a 分配兼容ListMap。因此,您需要使用委托代理包装返回的对象。首先,为List. 它们很容易创建,例如 Eclipse 可以通过Generate Delegate Methods...从“ Source”下拉菜单中选择“ ”为您创建所有委托方法。它应该如下所示:public class DelegatingList<E> implements List<E> {&nbsp; &nbsp; private final List<E> list;&nbsp; &nbsp; protected DelegatingList(List<E> list) {&nbsp; &nbsp; &nbsp; &nbsp; this.list = list;&nbsp; &nbsp; }&nbsp; &nbsp; @Override&nbsp; &nbsp; public int size() {&nbsp; &nbsp; &nbsp; &nbsp; return this.list.size();&nbsp; &nbsp; }&nbsp; &nbsp; @Override&nbsp; &nbsp; public boolean isEmpty() {&nbsp; &nbsp; &nbsp; &nbsp; return this.list.isEmpty();&nbsp; &nbsp; }&nbsp; &nbsp; @Override&nbsp; &nbsp; public boolean contains(Object o) {&nbsp; &nbsp; &nbsp; &nbsp; return this.list.contains(o);&nbsp; &nbsp; }&nbsp; &nbsp; // many other delegating methods from List}现在定义你的ListMap界面:public interface ListMap extends List<Map<String,Object>> {&nbsp; &nbsp; public static ListMap newArrayList() {&nbsp; &nbsp; &nbsp; &nbsp; return wrap(new ArrayList<>());&nbsp; &nbsp; }&nbsp; &nbsp; public static ListMap wrap(List<Map<String,Object>> list) {&nbsp; &nbsp; &nbsp; &nbsp; if (list instanceof ListMap)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return (ListMap) list;&nbsp; &nbsp; &nbsp; &nbsp; class Wrapper extends DelegatingList<Map<String,Object>> implements ListMap {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; protected Wrapper() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; super(list);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return new Wrapper();&nbsp; &nbsp; }}现在使用起来很简单:ListMap myListMap = ListMap.newArrayList();methodAcceptingListOfMapOfStringToObject(myListMap);ListMap x = ListMap.wrap(methodReturningListOfMapOfStringToObject());
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java