Android 6.0 (Marshmallow) svg-android 库中 getDeclaredField() 的静态初始化异常

Android 6.0 (Marshmallow) static initialization exception on getDeclaredField() in svg-android library

我在使用这段代码时遇到了一些严重的问题,来自 svg-android:

public class ParserHelper {

private static final Field STRING_CHARS;
static {
    try {
        STRING_CHARS = String.class.getDeclaredField("value"); //<-- exception here
        STRING_CHARS.setAccessible(true);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

private final char[] s;
private final int n;
private char current;
public int pos;

public ParserHelper(String str, int pos) {
    try {
        this.s = (char[]) STRING_CHARS.get(str); 
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    this.pos = pos;
    n = s.length;
    current = s[pos];
}

STRING_CHARS = String.class.getDeclaredField("value");抛出异常

10-09 10:25:58.240: E/AndroidRuntime(3430): Caused by: java.lang.RuntimeException: java.lang.NoSuchFieldException: No field value in class Ljava/lang/String; (declaration of 'java.lang.String' appears in /system/framework/core-libart.jar)

我无法继续工作。仅在 Android 6.0 Marshmallow 中。有什么想法吗?

已解决: 现在,我没有解决静态初始化问题,但我更改了 char[] s 初始化:

public class ParserHelper {

//  private static final Field STRING_CHARS;
//  static {
//      try {
//          STRING_CHARS = String.class.getDeclaredField("value");
//          STRING_CHARS.setAccessible(true);
//      } catch (Exception e) {
//          throw new RuntimeException(e);
//      }
//  }

    private final char[] s;
    private final int n;
    private char current;
    public int pos;

    public ParserHelper(String str, int pos) {
        try {
            s = new char[str.length()];
            str.getChars(0, str.length(), this.s, 0); //<-- here
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        this.pos = pos;
        n = s.length;
        current = s[pos];
    }

看起来 String 的私有字段 value 包含字符数组,在 Marshmallow 中已重命名为 ASCII。因此,您在这些行中有一个 RuntimeException(取自 com.larvalabs.svgandroid.ParserHelper class):

    try {
        STRING_CHARS = String.class.getDeclaredField("value");
        STRING_CHARS.setAccessible(true);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

svgandroiddiscontinued, so there is little chance that the project's author will fix this issue and push the new jar to maven.You can make your own fork of svgandroid library, merge this pull-request,构建 jar 并从现在开始使用它,而不是 mavenized 版本。

或者你可以更进一步,自己push固定版本到mvnrepository。 :)