首页 > 解决方案 > 如何在其他类中注入父类,以便它根据传递的模型选择子类?

问题描述

我在 Java 中有以下类

class A which is inherited by class A1 and A2

A has method run and both A1, A2 are overriding this method

Another model class B

B has JSON subtypes B1 and B2 (child classes)

我现在想要实现的是如果我跑

InstanceOfA.run(B) where B is a reference to B1 subtype, it should execute A1's run method

and If I run InstanceOfA.run(B) where B is a reference to B2 subtype, It should execute A2's run method.

InstanceOfA 是 A 的一个实例。

如果这是可能的,我可以在所有其他类(需要它的地方)中使用 @Inject 注释注入 A 并且不需要传递实际的实现。

也欢迎任何其他解决方案。

标签: javaoopdesign-patternsdependency-injection

解决方案


推荐阅读