这里是所有 Android 程序员的问题:
在我的应用中使用新旧 API 方法时,我发现了两种方法来处理不同的 API 方法。
测试 SDK_INT
if (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 不会被视为“干净”。
但是:在移动设备上,哪种方法是首选?从长远来看,哪个更快?
谢谢大家的意见!
最佳答案
which is the preferred approach?
恕我直言,使用Build
。
Which one is faster on the long run?
构建
。
更重要的是,Build
告诉您什么是支持,因为您正在阅读 JavaDocs 并根据该文档决定是否做某事。
公共(public)Java类上有很多公共(public)方法,其中类在Android SDK中,但方法不在。那些在 AOSP 源代码中被标记为 @hide
并且在创建我们链接到的 android.jar
时,在创建 JavaDocs 等时被删除。那些代表方法在 Android 团队看来“还没有准备好迎接黄金时段”,但需要在框架内公开供内部使用。反射技术将愉快地报告此类隐藏方法可供使用,即使:
由于 Android 团队变更或制造商变更,它们的方法签名可能与最终在 SDK 中发布的方法签名(参数、返回类型、异常)不同
这些隐藏方法的行为没有记录,因此可能与发布这些方法时记录的功能不匹配
我是大@Macarse粉丝,但这是一个我们必须同意不同意的情况。
关于android - 您是愿意使用测试 Build.VERSION.SDK_INT 还是反射来测试是否存在?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17449831/