-1
abstract class A {}
class B extends A {}
class C extends A {}
List<A> items = // objects of B,C types
items.stream.map(item -> build(item));

How to keep different logic in build method for type B and C. I've tried to declare build(B b) and build(C c) as I thought it checks the actual type in the runtime but it looks it checks declared type. I can use instanceof but think there should be a better way. B,C are entity beans thus cannot add my logic there

ra74
  • 129
  • 1
  • 10
  • I don't think this is an appropriate use of streams. Streams should not be modifying external data structures. – WJS Nov 27 '20 at 14:30
  • You will probably have to check what instance are you working with in some handler and then handle separately. `A.class` should not include logic for handling specific classes that extend it, that just feels like an anti-pattern. – Dropout Nov 27 '20 at 14:45
  • @ra74 But this whole concept feels hackish. Normally both `B.class` and `C.class` would implement some interface which allows them to build, i.e. have both implement `IBuildable` and define `Ibuildable::build` method in both `B.class` and `C.class`. That's the *normal* way to go. I know you probably can't do anything about this, just needed to get it off my chest. – Dropout Nov 27 '20 at 14:50
  • in my case the stream doesn't modify anything. A,B,C are hibernate entities that describe some hierarchical tree metadata and I'm using swagger fluent api to build corresponding json schema model. Actually it uses builder pattern. – ra74 Nov 27 '20 at 15:01

1 Answers1

1

If you can't add build() methods to classes A, B and C, you can't use polymorphism. So, you have to do runtime if statements, based on instanceof (unless you have some better indicator instead of the instance class).

Ralf Kleberhoff
  • 6,990
  • 1
  • 13
  • 7
  • actually I've getType() method - hibernate discriminator is based on that field. Normally I treat using instanceof as sth is wrong wih the design but I don't see a better solution without overengeering – ra74 Nov 27 '20 at 15:14