在编译Android Studio(JAVA)程序时发生了如下的警告:
使用了未经检查或不安全的操作
要了解详细信息,请使用 "-Xlint:unchecked" 重新编译。
- 如何设置Android Stuido开启 "-Xlint:unchecked"
修改build.gradle
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
apply plugin: 'com.android.application' android { compileSdkVersion 23 buildToolsVersion "23.0.1" defaultConfig { applicationId "com.a.b.c" minSdkVersion 15 targetSdkVersion 23 versionCode 1 versionName "1.0" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } debug { minifyEnabled false } } } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) testCompile 'junit:junit:4.12' compile 'com.android.support:appcompat-v7:23.0.1' compile 'com.android.support:design:23.0.1' } |
增加
1 2 3 |
tasks.withType(JavaCompile) { options.compilerArgs << "-Xlint:unchecked" } |
修改后的如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
apply plugin: 'com.android.application' android { compileSdkVersion 23 buildToolsVersion "23.0.1" defaultConfig { applicationId "com.a.b.c" minSdkVersion 15 targetSdkVersion 23 versionCode 1 versionName "1.0" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } debug { minifyEnabled false } } tasks.withType(JavaCompile) { options.compilerArgs << "-Xlint:unchecked" } } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) testCompile 'junit:junit:4.12' compile 'com.android.support:appcompat-v7:23.0.1' compile 'com.android.support:design:23.0.1' } |
- 警告信息的处理例子
包含-Xlint:unchecked警告的代码
1 2 3 4 5 6 |
final LinkedHashMap<WeakReference<Object>,WeakReference<Object>> aWeakArray = new LinkedHashMap<>(); for (Iterator iter = aWeakArray.entrySet().iterator(); iter.hasNext(); ) { LinkedHashMap.Entry element = (LinkedHashMap.Entry)iter.next(); WeakReference<Object> aWeakObj = (WeakReference<Object>)element.getKey(); WeakReference<Object> aWeakTag = (WeakReference<Object>)element.getValue(); } |
消除警告后的代码如下:
1 2 3 4 5 6 |
final LinkedHashMap<WeakReference<Object>,WeakReference<Object>> aWeakArray = new LinkedHashMap<>(); for (Iterator<LinkedHashMap.Entry<WeakReference<Object>,WeakReference<Object>> > iter = aWeakArray.entrySet().iterator(); iter.hasNext(); ) { LinkedHashMap.Entry<WeakReference<Object>,WeakReference<Object>> element = iter.next(); WeakReference<Object> aWeakObj = element.getKey(); WeakReference<Object> aWeakTag = element.getValue(); } |
同样的方法适用于"-Xlint:deprecation"。