与SDK_INT黑客的Andr​​oid解决兼容性;这个可以吗?兼容性、黑客、SDK_INT、oid

2023-09-07 02:25:45 作者:放你去浪

运行如下(注:目标> 3.0)

Running the following (note: target > 3.0)

ActionBar actionBar = getActionBar();

在Android版本< 3.0(SDK 11)的结果是的NoSuchMethodError

有几种方法来解决这个问题,包括反射和类懒加载。但是,以下似乎在所有我测试过的设备上班(2.3.6,3.0,3.1,4.0):

There are several ways to get around this, including reflection and class lazy loading. However, the following seems to work across all the devices I've tested (2.3.6, 3.0, 3.1, 4.0):

boolean hasActionBar = android.os.Build.VERSION.SDK_INT >= 11;

if (hasActionBar) {
    ActionBar actionBar = getActionBar();
} else {
    // create custom actionbar
}

注意 SDK_INT 参数静态最后,这似乎可以解释为什么这个工作的。

Note the SDK_INT parameter is static final, which appears to be why this works.

这是对付兼容性的有效方法是什么?

Is this a valid way to deal with compatibility?

推荐答案

它看起来像这样的作品由于JIT编译器。这code未能在SDK< 2.1,支持这一理论。无论如何,这可能不是一个可靠的方法,以避免反光。

It looks like this works due to the JIT compiler. This code fails on SDK < 2.1, which supports this theory. Regardless, this probably isn't a reliable way to avoid reflection.