标签:
最近在读项目源码的时候,发现一个SharedPreferencesCompat类,这个类做了一些简单的工作,后来google之后理解了这种写法的缘由,在这里跟大家分享一下。
首先我们直接来看这个类的源码,很简短
/**
* Reflection utils to call SharedPreferences$Editor.apply when possible,
* falling back to commit when apply isn't available.
*/
public class SharedPreferencesCompat {
private static final Method sApplyMethod = findApplyMethod();
private static Method findApplyMethod() {
try {
Class cls = SharedPreferences.Editor.class;
return cls.getMethod("apply");
} catch (NoSuchMethodException unused) {
// fall through
}
return null;
}
public static void apply(SharedPreferences.Editor editor) {
if (sApplyMethod != null) {
try {
sApplyMethod.invoke(editor);
return;
} catch (InvocationTargetException unused) {
// fall through
} catch (IllegalAccessException unused) {
// fall through
}
}
editor.commit();
}
}
从上面的代码我们可以看出,首先在findApplyMethod()方法里面,我们通过反射获得Editor的apply()对象,这个对象是一个final static,并且findApplyMethod()方法是静态调用的,也就是我们一旦使用了这个类,就首先获得了一个apply()方法对象。
接着,我们看public方法apply(),传入的是一个Editor对象,sApplyMethod不为空,则通过反射调用Editor的apply()方法,否则呢,调用Editor的commit()方法
在这里我们的疑惑是,什么时候sApplyMethod可能为空呢。这里涉及了一个api版本问题,Editor的apply()是在API 9以后新增的,所以为了兼容API 9以下的版本,当我们没有aplly()方法的时候,才调用commit()方法。
OK,说到这里,这个类的作用解决了,但是可能又有一个疑惑,apply()和commit()方法有什么区别呢?
apply()是新增的,目的是为了提高commit()方法的效率问题。
版权声明:本文为博主原创文章,未经博主允许不得转载。
SharedPreferencesCompat的由来与简单解析
标签:
原文地址:http://blog.csdn.net/crazy__chen/article/details/47026845