Determining the Efferent coupling between objects (CBO Metric) using the parsed byte-code generated by BCEL

旧街凉风 提交于 2019-12-11 06:51:41

问题


I have built a program, which takes in a provided ".class" file and parses it using the BCEL, I've learnt how to calculate the LCOM4 value now. Now I would like to know how to calculate the CBO(Coupling between object) value of the class file. I've scoured the whole web, trying to find a proper tutorial about it, but I've been unable so far (I've read the whole javadoc regarding the BCEL as well and there was a similar question on stackoverflow but it has been removed). So I would like some help with this issue, as in some detailed tutorials or code snippets that would help me understand on how to do it.


回答1:


OK, here you must compute the CBO of the classes within a whole set of classes. The set can be the content of a directory, of a jar file, or all the classes in a classpath.

I would fill a Map<String,Set<String>> with the class name as the key, and the classes it refers to:

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);
    }
}

When you've added all the classes in the map, you need to filter the referees of each class to limit them to the set of classes considered, and add the backward links:

            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);
                }
            }


来源:https://stackoverflow.com/questions/44061843/determining-the-efferent-coupling-between-objects-cbo-metric-using-the-parsed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!