难以理解嵌套集合

时间:2013-05-29 01:10:05

标签: java collections nested bytecode

我正在使用字节码在java中动态生成类,然后加载类。我在教程中找到了这个代码,如何做到这一点。

  private int stringConstant(String s) {
        return constant(CONSTANT_Utf8, s);
    }

    private int classConstant(String s) {
        int classNameIndex = stringConstant(s.replace('.', '/'));
        return constant(CONSTANT_Class, classNameIndex);
    }

    private int constant(Object... data) {
        List<?> dataList = Arrays.asList(data);
        if (poolMap.containsKey(dataList))
            return poolMap.get(dataList);
        poolMap.put(dataList, poolIndex);
        return poolIndex++;
    }

    private void writeConstantPool(DataOutputStream dout) throws IOException {
        dout.writeShort(poolIndex);
        int i = 1;
        for (List<?> data : poolMap.keySet()) {
            assert(poolMap.get(data).equals(i++));
            int tag = (Integer) data.get(0);
            dout.writeByte(tag);          // u1 tag
            switch (tag) {
                case CONSTANT_Utf8:
                    dout.writeUTF((String) data.get(1));
                    break;                // u2 length + u1 bytes[length]
                case CONSTANT_Class:
                    dout.writeShort((Integer) data.get(1));
                    break;                // u2 name_index
                default:
                    throw new AssertionError();
            }
        }
    }

    private final Map<List<?>, Integer> poolMap =
            new LinkedHashMap<List<?>, Integer>();
    private int poolIndex = 1;

我不明白如何使用包含列表的地图,这似乎不是传统的oop方式来做这类事情。

1 个答案:

答案 0 :(得分:0)

在您给我们的片段中,地图是一种将唯一索引(从1增加)分配到您放入其中的每个List的方法。这个索引显然只是 assert中用来检查密钥的检索顺序与它们的插入顺序相同 - 考虑到地图是{{1 }}

就给定的代码而言,LinkedHashMap也可以。当然我们不知道调用LinkedHashSet等的地方,也许调用者可以使用索引。

从OO的角度来看,我没有反对意见 - 首先对这个代码片段几乎没有任何反对意见。