【发布时间】:2014-10-06 22:27:41
【问题描述】:
我一直在使用 Fields 将类解析为 SharedPreferences。它在设置类不是单例时起作用。我改成单身人士工作,但它不再工作了。
G2ASettings settings = G2ASettings.getInstance();
Field[] fields = G2ASettings.class.getDeclaredFields();
for (Field f : fields) {
f.setAccessible(true);
try {
if (preferences.contains(f.getName()) && !f.getName().equals("INSTANCE")) {
f.set(settings, preferences.getBoolean(f.getName(), f.getBoolean(settings))); //si no lo encuentra, pone el valor por defecto determinado en la clase
} else {
if (blablabla) {
editor.putBoolean(f.getName(), true);
allPreferencesDisabled = true;
} else
(*)-----> editor.putBoolean(f.getName(), f.getBoolean(settings));
}
(*)-----> if (!allPreferencesDisabled) allPreferencesDisabled = f.getBoolean(settings);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
报错如下:
Caused by: java.lang.IllegalArgumentException: not a primitive field
在代码中标记为 (*) 的行处报告了错误。
G2ASettings 的字段都是 public 和 boolean 除了 INSTANCE 变量是 G2ASettings 类型变量并且是私有的。
我将在这里报告我的进度。
EXTRA:我这里只发布G2ASettings类(通常的Singleton类)的相关数据:
public class G2ASettings implements Serializable {
public boolean {big amount of boolean variables]
private static G2ASettings INSTANCE = null;
private synchronized static void createInstance() {
if (INSTANCE == null) {
INSTANCE = new G2ASettings();
}
}
public static G2ASettings getInstance() {
if (INSTANCE == null) createInstance();
return INSTANCE;
}
{public getters and setters}
}
【问题讨论】:
-
如果您发布一个简短但完整的程序来演示该问题,这将非常有帮助。这里有很多不太可能相关的东西,但如果我们能真正为自己重现它,那将是非常有用的。
-
editor.putBoolean 是做什么的?
-
抛出此异常时您所在的字段是哪个字段?我敢打赌它是实例,正如你所说,它不是布尔值,所以你不能调用
getBoolean()。在尝试获取其布尔值之前检查当前字段是否不是 INSTANCE 的 if 语句需要更早并涵盖所有其他逻辑,因为 INSTANCE 永远不会有布尔值并且不应该被持久化。跨度> -
@Leo,我发布的函数检查 SharedPreferences 是否具有所有必需的字段(这些是 G2ASettings 类的字段)。如果缺少字段,则添加该字段及其值(使用 editor.putBoolean)。