【发布时间】:2014-09-14 16:23:33
【问题描述】:
我已经看到了一些用于计算 Linux 和 MacOS 上的方法的链接,但我还没有看到任何适用于 Windows 的链接。如何计算 .dex 或 .jar 文件中的方法数?
【问题讨论】:
我已经看到了一些用于计算 Linux 和 MacOS 上的方法的链接,但我还没有看到任何适用于 Windows 的链接。如何计算 .dex 或 .jar 文件中的方法数?
【问题讨论】:
在寻找解决方案失败后,我编写了两个简单的批处理/shell 脚本来执行此操作。
第一个,methodcount.bat,检查文件是.dex还是.jar,如果是.jar文件,它用dx处理成dex文件,然后调用第二个,printhex.ps1,实际上检查 dex 文件中方法的数量 - 它从 88(小端)开始读取 2 个字节并将它们转换为十进制数。
要使用它,您需要在路径中的某处安装 dx(它位于 android SDK build-tools/xx.x.x 文件夹中)并安装 PowerShell(它应该已经安装在 Windows 7/8 上)。
用法很简单:methodcount.bat filename.dex|filename.jar。
这里是脚本,但您也可以在 gist 上找到它们:https://gist.github.com/mrsasha/9f24e129ced1b1db791b。
methodcount.bat
@ECHO OFF
IF "%1"=="" GOTO MissingFileNameError
IF EXIST "%1" (GOTO ContinueProcessing) ELSE (GOTO FileDoesntExist)
:ContinueProcessing
set FileNameToProcess=%1
set FileNameForDx=%~n1.dex
IF "%~x1"==".dex" GOTO ProcessWithPowerShell
REM preprocess Jar with dx
IF "%~x1"==".jar" (
ECHO Processing Jar %FileNameToProcess% with DX!
CALL dx --dex --output=%FileNameForDx% %FileNameToProcess%
set FileNameToProcess=%FileNameForDx%
IF ERRORLEVEL 1 GOTO DxProcessingError
)
:ProcessWithPowerShell
ECHO Counting methods in DEX file %FileNameToProcess%
CALL powershell -noexit -executionpolicy bypass "& ".\printhex.ps1" %FileNameToProcess%
GOTO End
:MissingFileNameError
@ECHO Missing filename for processing
GOTO End
:DxProcessingError
@ECHO Error processing file %1% with dx!
GOTO End
:FileDoesntExist
@ECHO File %1% doesn't exist!
GOTO End
:End
printhex.ps1
<#
.SYNOPSIS
Outputs the number of methods in a dex file.
.PARAMETER Path
Specifies the path to a file. Wildcards are not permitted.
#>
param(
[parameter(Position=0,Mandatory=$TRUE)]
[String] $Path
)
if ( -not (test-path -literalpath $Path) ) {
write-error "Path '$Path' not found." -category ObjectNotFound
exit
}
$item = get-item -literalpath $Path -force
if ( -not ($? -and ($item -is [System.IO.FileInfo])) ) {
write-error "'$Path' is not a file in the file system." -category InvalidType
exit
}
if ( $item.Length -gt [UInt32]::MaxValue ) {
write-error "'$Path' is too large." -category OpenError
exit
}
$stream = [System.IO.File]::OpenRead($item.FullName)
$buffer = new-object Byte[] 2
$stream.Position = 88
$bytesread = $stream.Read($buffer, 0, 2)
$output = $buffer[0..1]
#("{1:X2} {0:X2}") -f $output
$outputdec = $buffer[1]*256 + $buffer[0]
"Number of methods is " + $outputdec
$stream.Close()
【讨论】:
printhex.ps1 而不使用 -noexit 选项:@echo "START" >mc_res.txt \n @for /F "tokens=*" %%t in (mc.txt) do (\n call methodcount.bat %%t >>mc_res.txt\n )\n@rem mc.txt contains a list of jar file names. '\n' means a newline
我看到这个问题很老了,但是有一个 Gradle 插件可以在 Windows 上运行,它会在每次构建时报告 APK 中的方法引用计数:https://github.com/KeepSafe/dexcount-gradle-plugin。
【讨论】:
meaningless to talk about method count in jar 一个有争议的问题。我提到这个解决方案没有解决 JAR 文件只是因为 OP 询问了 JAR 文件。