Unknown annotations are not ignored in Class.getAnnotations on Android Jelly Bean

Problem

According to JSR-175, the java specification, if annotation is not available at run time, it should be ignored. But in Android API 15-16, calling getDeclaredAnnotations() throws a NoClassDefFoundError exception. The API 17+ works as expected without exception.

See the sample project below for more details.

Question

What workaround would you suggest? Do you know about the corresponding Android error report? I could not find him.

Example

We have a sample class with @Nullable annotation:

 public class SampleClass { @Nullable private String _content; } 

@Nullable is available during the build process, but we exclude it from apk (to calculate the number of labels), in the example we do it as follows:

 configurations { provided } android.applicationVariants.all { variant -> variant.javaCompile.classpath += configurations.provided } dependencies { provided group: 'com.google.code.findbugs', name: 'jsr305', version: '3.0.2' } 

In MainActivity we will try to get all annotations from the _content field:

 Class clazz = SampleClass.class; Field[] fields = clazz.getDeclaredFields(); Field field = clazz.getDeclaredField("_content"); Annotation[] annotations = field.getDeclaredAnnotations(); // this line is throwing exception on API 15-16 

As a result, we get an exception in Android API 15-16:

 11-24 17:06:49.874 2146-2146/? E/AndroidRuntime: FATAL EXCEPTION: main java.lang.NoClassDefFoundError: javax/annotation/Nullable at java.lang.reflect.Field.getDeclaredAnnotations(Native Method) at java.lang.reflect.Field.getDeclaredAnnotations(Field.java:204) at im.getsocial.checkannotation.MainActivity.checkReflection(MainActivity.java:26) at im.getsocial.checkannotation.MainActivity.onCreate(MainActivity.java:15) at android.app.Activity.performCreate(Activity.java:5008) ... Caused by: java.lang.ClassNotFoundException: javax.annotation.Nullable at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:61) at java.lang.ClassLoader.loadClass(ClassLoader.java:501) at java.lang.ClassLoader.loadClass(ClassLoader.java:461) at java.lang.reflect.Field.getDeclaredAnnotations(Native Method) at java.lang.reflect.Field.getDeclaredAnnotations(Field.java:204) at im.getsocial.checkannotation.MainActivity.checkReflection(MainActivity.java:26) at im.getsocial.checkannotation.MainActivity.onCreate(MainActivity.java:15) at android.app.Activity.performCreate(Activity.java:5008) ... 

A complete sample project is available here: http://take.ms/Li3NF

Interestingly, there was a similar problem on Java 5: http://bugs.java.com/view_bug.do?bug_id=6322301

Update

  • January 27: sample example and compilation errors fixed
+5
source share

Source: https://habr.com/ru/post/1273636/


All Articles