Reputation: 1935
I have 3rd party data model class, where some fields and methods are private. I want hack this class to wrap these private fields to be accessible externally.
For example the data model is defaultModel.java. I want extend it to create a sub class RefineddefaultModel.java, which wraps its private field by using Java reflection.
Are there any good design patterns do this?
Because I felt only in my sub class to reflect it somehow it is not best practice.
Upvotes: 2
Views: 463
Reputation: 7531
Are there any good design patterns do this?
NO! Messing with private fields is the root to all evil, so there is no good way. You can (and most likely will) violated class invariants and concurrency support, risk incompatibility with future versions and will end up with a lot of unexpected behaviour at runtime. The fact that you need to, is a sign that something is seriously wrong with you design or how you use libraries.
If you asked: Is it possible in a horrible way? the answer is yes. You can do something like this.
// Possible but horrible:
Field field = object.getClass().getDeclaredField("privateField");
field.setAccessible(true);
oldValue = field.get(object);
field.set(object, newValue);
If you want things not to get completely out of hand only do gets and never do sets. I would further avoid extending the object and messing with the class structure. You can use the Adapter pattern using composition for this.
If any of the fields are final you might get additional problems. See this existing question: Changing private final fields via reflection. You can also see How do I read a private field in Java?
But I must stress this: Try hard to avoid this and make your future self happy. :)
Upvotes: 3