Check if method exists

房东的猫 提交于 2019-12-25 16:04:07

问题


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();
}

回答1:


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);




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/6782440/check-if-method-exists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!