Android如何优雅地防止Bean类混淆
生活随笔
收集整理的這篇文章主要介紹了
Android如何优雅地防止Bean类混淆
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
相信大家在開發(fā)Android app都會遇到一個問題:在打release包時bean類常常被混淆,導(dǎo)致出現(xiàn)空指針進(jìn)而引發(fā)crash
如何做到保持指定的類不被混淆?方法不止一個
1、 在混淆配置文件中添加bean類包名,這樣該包下所有的bean類都可以不被混淆了
-keep public class yourBeanPackageName.**{*;}2、 使用@keep注解(推薦)
Android support library從19.1版本開始引入了一個新的注解庫,它包含很多有用的元注解,你能用它們修飾你的代碼,幫助你發(fā)現(xiàn)bug;你只要引用appcompat庫或者support library就可以使用該注解了
dependencies {compile 'com.android.support:support-annotations:versionNum'//兩選一compile 'com.android.support:appcompat-versionNum'//兩選一 }keep注解的定義
@Retention(CLASS) @Target({PACKAGE,TYPE,ANNOTATION_TYPE,CONSTRUCTOR,METHOD,FIELD}) public @interface Keep { }我們可以看出keep注解可以作用于包、類、接口、注解類型、構(gòu)造器、方法、字段上,@那里,那里就可以不混淆是不是很方便;
注意: 如果你的Android SDK Tools版本足夠高(>24),那么在proguard-rules.pro文件其實不用做任何改動,因為Google已經(jīng)幫我們在proguard-android.txt文件配置好了(如果較低就把下面代碼拷貝到proguard-android.txt中),具體相關(guān)配置如下:
# The support library contains references to newer platform versions. # Don't warn about those in case this app is linking against an older # platform version. We know about them, and they are safe. -dontwarn android.support.** # Understand the @Keep support annotation. -keep class android.support.annotation.Keep -keep @android.support.annotation.Keep class * {*;} -keepclasseswithmembers class * { @android.support.annotation.Keep <methods>; }-keepclasseswithmembers class * { @android.support.annotation.Keep <fields>; }-keepclasseswithmembers class * { @android.support.annotation.Keep <init>(...); }3、 自定義注解
自定義注解原理其實和Keep一樣,這里不在闡述了
總結(jié)
以上是生活随笔為你收集整理的Android如何优雅地防止Bean类混淆的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Android之Badge显⽰
- 下一篇: 自定义Java注解(一)