Java 从 Android Studio 项目中删除所有未使用的类和方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37066506/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Remove all unused classes,methods from Android Studio project
提问by bilal
I have used the lint(Analyze->InspectCode...) and find out unused methods and resources. All the unused resources removed by Refractor->Remove unused Resourcesbut not found any option like this to remove java classes and methods. Is there any feature in the android studio or any Plugin which can remove all the java classes, the methods which are not used in code to save manual refracting?
我使用了 lint(分析->检查代码...)并找出未使用的方法和资源。由Refractor->Remove used Resources 删除的所有未使用的资源,但没有找到任何这样的选项来删除 java 类和方法。android studio 或任何插件中是否有任何功能可以删除所有 java 类,代码中未使用的方法来保存手动折射?
回答by bilal
Android ships with ProGuard and can do what you want. If you are using Gradle as build system then you can add the following lines in your build.gradle
file:
Android 附带 ProGuard,可以为所欲为。如果您使用 Gradle 作为构建系统,那么您可以在build.gradle
文件中添加以下几行:
android {
// ... other configurations
buildTypes {
release {
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android.txt')
signingConfig signingConfigs.release
}
debug {
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android.txt'),
'proguard-rules-debug.pro'
}
}
}
Your proguard-rules-debug.pro
file only needs to contain one line
您的proguard-rules-debug.pro
文件只需要包含一行
-dontobfuscate
With this additions your release build will get shrunk and obfuscated, your debug build, however, will get only shrunk, i.e, unnecessary code is removed. Note, that ProGuard operates on the build and not the source code.
通过这些添加,您的发布版本将缩小和混淆,但是,您的调试版本只会缩小,即删除不必要的代码。请注意,ProGuard 对构建而不是源代码进行操作。
The ProGuard FAQhas some more information of what it can do.
该ProGuard的常见问题有什么可以做一些更多的信息。
回答by KursoR
This can be achieved by using the built-in inspection Java | Declaration redundancy | Unused declaration
.
这可以通过使用内置检查来实现Java | Declaration redundancy | Unused declaration
。
To run it on whole project go to Analyze -> Run inspection by name...
, type Unused declaration
and select desired scope.
Then carefully check output and mark some classes as entry points if needed.
要在整个项目上运行它,请转到Analyze -> Run inspection by name...
,键入Unused declaration
并选择所需的范围。然后仔细检查输出并在需要时将一些类标记为入口点。
Now you can select Unused declaration
node in list and perform Safe delete
action on all unused declarations at once.
现在您可以选择Unused declaration
列表中的节点并立即Safe delete
对所有未使用的声明执行操作。
For Kotlin there is similar inspection Kotlin | Redundant constructs | Unused symbol
.
对于 Kotlin,也有类似的检查Kotlin | Redundant constructs | Unused symbol
。