Home » Android » Android and reflection

Android and reflection

Posted by: admin April 23, 2020 Leave a comment


I get the impression that Android supports reflection. But does it really? How sensible would it be to rely on reflection heavily? What’s the penalty?

How to&Answers:

Android supports reflection.

Once you’ve got a prototype running, you can benchmark and determine your bottlenecks.

If its reflection, then consider trying to cache interfaces and such to make it a one-off cost, rather than continually resolving the same interfaces from the same instances repeatedly.


It is supported, and even recommended in the situation where you want compatibility with multiple versions of the Android OS in one apk file. This article from the official Android Developers Blog describes how to build an app that requires only some early version of the API, and uses reflection to invoke new APIs if they are available:

Backward compatibility for Android applications


a simple example related to using reflection on android http://aaarkonusurum.blogspot.com/2012/02/android-ile-reflection.html

Class x = Object.class;
Constructor[] constructors = x.getDeclaredConstructors();
Field[] fields = x.getDeclaredFields();
Method[] methods = x.getDeclaredMethods();
for (Constructor constructor : constructors) { 
for (Field field : fields) {
for (Method method : methods) {

Creating a TextView from codebehind at runtime with using reflection

String x = TextView.class.toString().replace("class ", "");
Class<?> cls = Class.forName(x);
Class<?> param[] = new Class[1];
param[0] = Context.class; //Context=o an ki context ==> [activity.class]
Constructor<?> ct = cls.getConstructor(param);
Object paramVal[] = new Object[1];
paramVal[0] = context;
Object retobj = ct.newInstance(paramVal); 

Reaching to setText() method at the runtime

Class methodParam[] = new Class[1];
methodParam[0] = java.lang.CharSequence.class;
Method method = cls.getMethod("setText", methodParam);
Object arglist[] = new Object[1];
method.invoke(retobj, arglist); 


There is a nice example of reflection in the sample code as well, in BusinessCard. This method wont result in a bunch of expections being thrown, so it should be much more performance friendly. It is also, in my opinion, easier to implement. Especially if it concerns a previously unimplemented method.

Here is where it is used:


Android of course supports Reflection and we can read methods of a different APK or Framework class.
Here is an article on using Reflection in Android as a possible design approach to create API-