Reputation: 1379
I am fairly new to java development and wounder how I can modify an existing Android class. I would like to change some of the methods in Notification.Builder
class in Android (https://github.com/android/platform_frameworks_base/blob/master/core/java/android/app/Notification.java).
Specifically do I want to change getNotification()
, but in the new implementation I need access to the private fields (e.g., mWhen
, mSmallIcon
).
I have tried to extend the class, but then I don't have access to the private fields of the superclass (i.e., mWhen
, mSmallIcon
).
What is the best practice to change the method, is it to copy the source code and modify it?
Update: To be more precise: how can I change a single method in an existing class and still have access to the private fields of the existing class?
Thanks for all responses!
Upvotes: 1
Views: 1170
Reputation: 41165
I have tried to extend the class, but then I don't have access to the private fields of the superclass (i.e., mWhen, mSmallIcon).
In the particular class you're extending there are a limited number of methods that set the values of these fields. You can override those methods to hold onto copies of the values in new fields in your subclass which you can then use in your override of getNotification()
.
This is something of a hack, and wouldn't be workable with a more complex class.
Another hack is to use reflection and invoke setAccessible(true)
on the field objects. This also may not be workable depending on security constraints.
If you say exactly the change you're trying to make, there might be a better way.
Upvotes: 0
Reputation: 73655
The best practice is not to override methods (from third-party classes which were not designed to be overridden), but to create a new class/method which wraps the third-party class. Google for these: "fragile base class problem", "composition over inheritance".
Upvotes: 0
Reputation: 346536
You could simply call super.getNotification()
in your overriden method and modify the resulting object before returning it.
Upvotes: 2
Reputation: 507
A private (inner) class, method or field are only referenced from within the class in which it is declared. But you also can declare your own variables and work with it as you wish
Upvotes: 0