Android Java Reflection


reflectionI have recently had to use reflection in Java. It allows you to develop with the latest SDK (say 2.01 or 2.1) while still allowing code to be run on older 1.x devices. Ordinarily, running (calling) newer APIs on older phones would cause errors.

Reflection is essentially a facility to test if an API exists. If it does then you can call the API. If it doesn’t then you can degrade gracefully with an error to the user or do something else instead.

There’s a great article on the Android Developers Blog explaining how it works.  It relies on a call to .class.getMethod() and catching a possible NoSuchMethodException.

Excessive use of reflection and/or not caching whether the api is there and/or using reflection repeatedly in time critical code, can cause performance problems. Also, this extra mechanism makes code less readable and, as more newer APIs become available, might make code harder to maintain.

One of the most useful places to use reflection is in testing. It allows common test harnesses to be built that can be run on both old and new code. Obviously, as it’s only test code, performance is less of an issue.

Comments are closed.