【发布时间】:2013-07-03 13:50:43
【问题描述】:
这是一个针对所有 Android 程序员的问题:
在我的应用中使用新旧 API 方法时,我发现了两种方法来处理不同的 API 方法。
-
在
中测试 SDK_INTif (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { holder.content.setBackground(background); } else { holder.content.setBackgroundDrawable(background); } -
编写一个“Compat”类,它使用反射来测试方法是否存在,如
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(final SharedPreferences.Editor editor) { if (sApplyMethod != null) { try { sApplyMethod.invoke(editor); return; } catch (InvocationTargetException unused) { // fall through } catch (IllegalAccessException unused) { // fall through } } editor.commit(); }
现在,后者取自 Carlos Sessa 的一本好书“50 Android hacks”。 我被教导使用异常处理来进行流控制是一件坏事,而且不应该这样做。如果您可以针对某些东西进行测试,请不要故意遇到异常处理。 因此,方法 2 不会被认为是“干净的”。
但是:在移动设备上,哪个是首选方法?从长远来看,哪个更快?
感谢您的所有意见!
【问题讨论】:
标签: android compatibility android-version