简体   繁体   中英

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. There are about 20 fields in a each vehicle. 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"); .. 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".)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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