简体   繁体   English

将豆作​​为许多具体类型之一

[英]Receiving a bean as one of many concrete types

I have a java bean inheritance hierarchy about five levels deep with many types of vehicle models as the deepest level subclasses. 我有一个大约五个级别的Java bean继承层次结构,其中许多类型的车辆模型是最深层次的子类。 There are about 20 fields in a each vehicle. 每辆车大约有20个场地。 I am having a factory return a particular vehicle model based on a value. 我正在让工厂根据值返回特定的车辆型号。 Then I have to use setters to set each of the twenty fields. 然后,我必须使用设置器来设置二十个字段中的每个字段。 But properties, and hence, setters depend on each model. 但是属性以及设置者取决于每个模型。 These models do not implement any interface. 这些模型不实现任何接口。 Even if they did, I would not be able to call setters on interface type that I receive the empty concrete type in. Is there a way to receive the reference into a concrete model type so I can call setters? 即使他们这样做了,我也无法在接收到空具体类型的接口类型上调用设置器。是否有办法将引用接收到具体模型类型中,以便我可以调用设置器? Rest of the class needs to use such a reference to call other methods. 该类的其余部分需要使用这样的引用来调用其他方法。

I'd like to receive one of the following: 我想收到以下其中一项:

Camry camry = Factory.get("DL");
Taurus taurus = Factory.get("BC");
Cadillac cadillac = Factory.get("ES");

Then use one of the references as appropriate. 然后,使用适当的参考之一。 cadillac.setStarSystem("star123"); cadillac.setStarSystem(“ star123”); .. all cadillac related setters ..所有与凯迪拉克相关的二传手

It is not essential to use a factory. 使用工厂不是必需的。 Any other technique will do. 任何其他技术都可以。

Thank you! 谢谢!

If you know what type you're going to be getting back, isn't this just a simple casting exercise? 如果您知道要恢复哪种类型,这不只是一个简单的转换练习吗? ("Any other technique will do"?) (“任何其他技术都可以使用吗?”)

Camry camry = (Camry)vehicles.get("DL");
Taurus taurus = (Taurus)vehicles.get("BC");
Cadillac cadillac = (Cadillac)vehicles.get("ES");

cadillac.setStarSystem("star123");

And no, you don't need to use any specific interfaces to do this. 不,您不需要使用任何特定的接口来执行此操作。 As shown / mentioned, this will allow you to "receive the reference into a concrete model type so I can call setters". 如显示/提及,这将使您“将参考接收到具体的模型类型中,以便我可以调用设置器”。

(One unfortunate side-effect of the generics introduced with Java 1.5/5.0 is that it sometimes causes users to forget about the basics of polymorphism - and all of the sudden, "casting is bad".) (Java 1.5 / 5.0引入的泛型的一个不幸的副作用是,它有时会导致用户忘记多态性的基础-突然之间,“广播很糟糕”。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM