Java/Android: Access private variables in a class using reflection

0 Comments

Android's DatePickerDialog class has a handy little function getDatePicker(), which exposes the private DatePicker mDatePicker.

Problem with that is it's only available on Honeycomb/API 11+. I don't want to raise my damn API level and leave 2.3 users behind! They're the majority of my users (at time of writing)

funny-gifs-table-flip

So, what can I do to get around this design oversight? Extending/subclassing the DatePickerDialog class won't work, because it's still a private variable.

Good thing is that even on Android, reflection is still a valid option. What reflection does is use Java's internal mechanisms to access the variable directly from the object.

01.public DatePicker getDatePicker() {
02.  try {
03.    Field field = DatePickerDialog.class.getDeclaredField("mDatePicker");
04.    field.setAccessible(true);
05.    return (DatePicker) field.get(datePickerDialog);
06.  }
07.  catch (NoSuchFieldException e) {
08.    e.printStackTrace();
09.  }
10.  catch (IllegalArgumentException e) {
11.    e.printStackTrace();
12.  }
13.  catch (IllegalAccessException e) {
14.    e.printStackTrace();
15.  }
16. 
17.  return null;
18.}

This little helper function works a treat! Unless the variable is renamed in other revisions of Android, it should work fine in all cases.

Sources

 
Copyright © Twig's Tech Tips
Theme by BloggerThemes & TopWPThemes Sponsored by iBlogtoBlog