【问题标题】:Count lines of code (LOC) for JAR and AARJAR 和 AAR 的代码行数 (LOC)
【发布时间】:2016-02-17 14:47:43
【问题描述】:

我们如何计算库文件中的代码行数。

例如,Jar 或 AAR。

注意 - CLOC 是一个很棒的工具,但不幸的是,它不处理“.class”文件。

转换 JAR -> DEX 和反编译 DEX -> 代码是一种方法,但在转换和反编译过程中可能会丢失精度。

【问题讨论】:

  • “我们如何计算库文件中的代码行数”——你不知道。那是一个毫无意义的概念。 “转换 JAR -> DEX 和反编译 DEX -> 代码,是一种方法,但在转换和反编译过程中可能会丢失精度”——然后强迫库的开发人员在枪口下交出源代码代码到库。请注意,这在某些司法管辖区可能是非法的。只有当您拥有源代码时,才能计算源代码行数。其他指标——类计数、方法计数等——可以在编译后的 Java/DEX 字节码上执行。

标签: android count dex lines-of-code


【解决方案1】:

在某些情况下,您可以使用 dex 文件中的调试信息大致了解行数。

使用 dexlib2,您可以执行以下操作:

public static void main(String[] args) throws IOException {
    DexFile dexFile = DexFileFactory.loadDexFile(args[0], 15);

    long lineCount = 0;

    for (ClassDef classDef: dexFile.getClasses()) {
        for (Method method: classDef.getMethods()) {
            MethodImplementation impl = method.getImplementation();
            if (impl != null) {
                for (DebugItem debugItem: impl.getDebugItems()) {
                    if (debugItem.getDebugItemType() == DebugItemType.LINE_NUMBER) {
                        lineCount++;
                    }
                }
            }
        }
    }

    System.out.println(String.format("%d lines", lineCount));
}

比较代码大小的另一个指标可能是 dex 文件中的指令数。例如

public static void main(String[] args) throws IOException {
    DexFile dexFile = DexFileFactory.loadDexFile(args[0], 15);

    long instructionCount = 0;

    for (ClassDef classDef: dexFile.getClasses()) {
        for (Method method: classDef.getMethods()) {
            MethodImplementation impl = method.getImplementation();
            if (impl != null) {
                for (Instruction instruction: impl.getInstructions()) {
                    instructionCount++;
                }
            }
        }
    }

    System.out.println(String.format("%d instructions", instructionCount));
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-25
    • 2016-11-13
    • 2021-02-11
    • 1970-01-01
    相关资源
    最近更新 更多