使用BCEL生成的解析字节码确定对象之间的传出耦合(CBO Metric)

时间:2017-05-19 05:05:38

标签: java bytecode bcel cbo

我已经构建了一个程序,它接受一个提供的“.class”文件并使用BCEL解析它,我已经学会了如何计算LCOM4值。现在我想知道如何计算类文件的CBO(对象之间的耦合)值。我已经搜索了整个网络,试图找到一个关于它的正确教程,但我到目前为止一直无法(我已经阅读了关于BCEL的整个javadoc,并且在stackoverflow上有一个类似的问题,但它已经去除)。所以我想对这个问题提供一些帮助,比如一些详细的教程或代码片段,可以帮助我理解如何做到这一点。

1 个答案:

答案 0 :(得分:0)

好的,在这里你必须计算一整套类中的类的CBO。该集合可以是目录,jar文件或类路径中的所有类的内容。

我会填充Map< String,Set< String>>以类名作为键,以及它引用的类:

private void addClassReferees(File file, Map<String, Set<String>> refMap)
        throws IOException {
    try (InputStream in = new FileInputStream(file)) {
        ClassParser parser = new ClassParser(in, file.getName());
        JavaClass clazz = parser.parse();
        String className = clazz.getClassName();
        Set<String> referees = new HashSet<>();
        ConstantPoolGen cp = new ConstantPoolGen(clazz.getConstantPool());
        for (Method method: clazz.getMethods()) {
            Code code = method.getCode();
            InstructionList instrs = new InstructionList(code.getCode());
            for (InstructionHandle ih: instrs) {
                Instruction instr = ih.getInstruction();
                if (instr instanceof FieldOrMethod) {
                    FieldOrMethod ref = (FieldInstruction)instr;
                    String cn = ref.getClassName(cp);
                    if (!cn.equals(className)) {
                        referees.add(cn);
                    }
                }
            }
        }
        refMap.put(className, referees);
    }
}

如果您已添加地图中的所有类,则需要过滤每个类的裁判以将其限制为所考虑的类集,并添加后向链接:

            Set<String> classes = new TreeSet<>(refMap.keySet());
            for (String className: classes) {
                Set<String> others = refMap.get(className);
                others.retainAll(classes);
                for (String other: others) {
                    refMap.get(other).add(className);
                }
            }
相关问题