2

I have a wrapper class and an object it is wrapping. I want to call wrapper.method() and have it equate to object.method() without explicitly defining it for wrapper.

Is this possible?

Because otherwise you have to copy and paste every single of object's methods because Java is all about encapsulation and making the object public would make rivers run red.

Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
  • 6
    You mean that you want to avoid explicitly writing delegating method calls? Just get your IDE to generate them, e.g. [in eclipse](http://stackoverflow.com/questions/15397108/fast-implement-wrapping-delegate-methods-in-eclipse). – Andy Turner Jul 20 '16 at 09:09
  • Sounds like a task where [aspect-oriented programming](https://en.wikipedia.org/wiki/Aspect-oriented_programming) might be useful. – Jesper Jul 20 '16 at 09:12
  • 1
    ++ide generation. In Netbeans, press alt-insert when the keyboard focus is inside the wrapper class, but not inside any of its methods, or right-click in such a place and select "Insert Code", then choose "Delegate method" - you can select multiple methods to delegate simultaneously. – daiscog Jul 20 '16 at 09:22
  • Without the fine NetBeans IDE you could first extend the class wíth that of the field, in the IDE do "override all methods" and then replace "super." with "field.". – Joop Eggen Jul 20 '16 at 09:27
  • Use a `Proxy` instead? – Mark Rotteveel Jul 20 '16 at 09:41
  • @AndyTurner Perfect! I never actually knew what delegate methods meant... It still kind of clutters up the class with a lot of functions but oh well, works fine. – David Joseph Jul 21 '16 at 04:20

2 Answers2

0

What about wrapper.getObject().method() call?? This should resolve your problem of copy-paste.

Edit after comment: Yup! It would defile the purpose of wrapping.

Anupam Jain
  • 101
  • 10
0

This is not possible in pure java, but you can achieve this with Lombok. See @Delegate. Note that the feature is marked as "experimental", so to be used with caution.

noscreenname
  • 3,314
  • 22
  • 30