我叫马修,使用ProGuard后在Android上反射方面遇到了一些问题。
我正在使用libgdx编写游戏,并需要动态获取字符串,我的代码如下:
package com.PACKAGE;
public class CLASS extends ANOTHER_CLASS{
(...)
private static void load(String fieldName) {
Field field;
String fileName;
try {
field = SOME_CLASS.class.getField(fieldName);
fileName = (String) field.get(null);
} catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {
throw new RuntimeException(e);
}
SOME_CLASS.SOME_METHOD.load(fileName);
}
(...)
private STH get(String fieldName) {
Field field;
String fileName;
try {
field = SOME_CLASS.class.getField(fieldName);
fileName = (String) field.get(null);
} catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {
throw new RuntimeException(e);
}
return SOME_CLASS.SOME_METHOD.get(fileName);
}
(...)
}
当我导出发布apk(编译正常)并运行游戏时,我遇到了NoSuchFieldException异常:
java.lang.RuntimeException: java.lang.NoSuchFieldException: FIELD_NAME
我需要在proguard-project.txt
中添加什么来处理这个问题?这个方法不起作用,我不知道该怎么办。
-keepclassmembers class com.PACKAGE.CLASS {
String fileName;
}
类的样子:
package com.ANOTHER_PACKAGE;
public class SOME_CLASS {
public static final String fieldName1 = "string I want";
public static final String fieldName2 = "string I want";
public static final String fieldName3 = "string I want";
}
更新:
感谢@Selvin,答案如下:
-keepclassmembers class ANOTHER_PACKAGE.SOME_CLASS {
public static final <fields>;
}
在
project-proguard.txt
中。现在它完美地工作了 :)
-keepclassmembers class com.PACKAGE.SOME_CLASS
吗? - Selvinfield.get(null)
是用于静态成员的吗?(我知道错误不在这里,但是)你需要传递SOME_CLASS的实例而不是null来获取非静态字段... - Selvin