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

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.

public DatePicker getDatePicker() {
try {
Field field = DatePickerDialog.class.getDeclaredField("mDatePicker");
field.setAccessible(true);
return (DatePicker) field.get(datePickerDialog);
}
catch (NoSuchFieldException e) {
e.printStackTrace();
}
catch (IllegalArgumentException e) {
e.printStackTrace();
}
catch (IllegalAccessException e) {
e.printStackTrace();
}

return null;
}

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