Can I get an anonymous class from the builder?

I know that I can create an anonymous class when I manually create an instance of it as follows:

ClassName c = new ClassName() { public void overridenMethod() { method body } } 

Some classes, however, use the builder pattern to create a new instance. My question is whether there is a trick that would allow me to create an anonymous class using the builder provided by its superclass.

+4
source share
2 answers

No, or at least not directly: in Java you cannot inherit an instance; you need to inherit from the class.

However, you can create an anonymous class that wraps the instance returned from the builder. You can call methods on the wrapped instance, as you wish, and override those that you need to override.

 final ClassName wrapped = builder.buildClassName(); ClassName c = new ClassName() { public void passedThroughMethod1() { wrapped.passedThroughMethod1() } public void overridenMethod() { method body } public void passedThroughMethod2() { wrapped.passedThroughMethod2() } }; 

At this point, c behaves like an instance of wrapped , with the exception of overridenMethod . Unfortunately, you cannot access protected wrapped members.

+4
source

If I understand the question correctly, you want the builder to return an instance of an anonymous type. If so, I would add the create method to the base class that the builder calls to create a new instance. In the output class, override create to return an instance of the anonymous class. This assumes that the builder has access to the base class instance. Another mechanism is to provide Supplier builder.

Supplier

+1
source

Source: https://habr.com/ru/post/1442335/


All Articles