Tutorial :Is this considered reflection and to what degree?


I have an Android application (java) that was working fine when compiled with the Android 1.6 SDK using the following code from the android.provider.Contacts class:

Uri baseUri = Contacts.Phones.CONTENT_FILTER_URL;  

When the 2.0 SDK came out, the android.provider.Contacts class was depreciated and replaced with android.provider.ContactsContract. In order to get one program to work on both 1.6 and 2.0, I compiled under 1.6 with the following change:

Uri baseUri = Contacts.Phones.CONTENT_FILTER_URL;  …  try {      Class<?> c = Class.forName("android.provider.ContactsContract$PhoneLookup");      baseUri = (Uri) c.getField("CONTENT_FILTER_URI").get(baseUri);  }       catch (Exception e) {             }  

Since I was compiling under 1.6, I could not import android.provider.ContactsContract since it is a class known only to 2.0. Is this considered reflection and to what degree?

Added Comment: After reading the "Reflection" chapter of "The Java Programming Language" (which I should have done first), I mostly now understand what you can do with reflection but a concise definition of reflection is not easy to come by. Your answers have helped to clarify what prompted my question - that once a class has been reflected on, and an instance of the class created using reflection, you can interact with the instance as if the class was new'ed.

Here is my meager attempt at a concise definition that is far from perfect and I am sure I will need to revise as I learn more:

Reflection is the indirect, dynamic inquiry, manipulation or invocation of class objects using class objects contained in java.lang.reflect or the Class or Package classes that requires initially accessing the class using a fully qualified string name.


I believe that is the very definition of Java reflection (more on Android reflection for multiple-version compatibility). I'm not sure what you mean by "to what degree"; it just is.


Dynamically asking for the availability of a method is a form of reflection, yes.


It's reflection.

If CONTENT_FILTER_URI is a final static field, then you should use get(null) instead of get(baseUri) because you are not invoking an object.


I was a bit confused by your code. As I understand your snippet, first you assign Contacts.Phones.CONTENT_FILTER_URL to URL baseUri, then you reflect the CONTENT_FILTER_URI field on the PhoneLookup class and read that fields value from the URL instance stored in baseUri - just to assign the value to baseUri again !? Typo or room for improvement?


This is a very good article on strategies, reflection and other more sophisticated things, for using new APIs while remaining compatible with older platforms:


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »