Check if method exists

2019-08-17 02:09发布

I want to check if the method Camera.Parameters.getHorizontalViewAngle() exists on the device (it's only available from API 8 and my min SDK API is 7). I tried to use "reflection", as explained here, but it catches an error saying the number of arguments is wrong:

java.lang.IllegalArgumentException: wrong number of arguments

Anybody could help?

Camera camera;
camera = Camera.open();
Parameters params = camera.getParameters();
Method m = Camera.Parameters.class.getMethod("getHorizontalViewAngle", new Class[] {} );
float hVA = 0;
try {
    m.invoke(params, hVA);
} catch (IllegalArgumentException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (IllegalAccessException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (InvocationTargetException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

3条回答
爷、活的狠高调
2楼-- · 2019-08-17 02:34

Personally, I recommend conditional class loading, where you isolate the new-API code in a class that you only touch on a compatible device. I only use reflection for really lightweight stuff (e.g., finding the right CONTENT_URI value to use for Contacts or ContactsContract).

For example, this sample project uses two implementations of an abstract class to handle finding a Camera object -- on a Gingerbread device, it tries to use a front-facing camera.

Or, this sample project shows using the action bar on Honeycomb, including putting a custom View in it, while still maintaining backwards compatibility to older versions of Android.

查看更多
一纸荒年 Trace。
3楼-- · 2019-08-17 02:35

I know this is a hack, but why can't you put the first call to the method in a try/catch of it's own, and nest the rest of your try/catch code in there. If the outer catch executes, the method doesn't exist.

查看更多
Anthone
4楼-- · 2019-08-17 02:36

m.invoke(params, hVA);

should be

m.invoke(params, null);

Camera.Parameters.getHorizontalViewAngle() doesn't take any arguments and the above line has the argument hVA. If you're looking for the return variable do hVA = m.invoke(params, null);

查看更多
登录 后发表回答