I'm trying to make a factory with Java generics. The problem is that I don't know how to retrieve in runtime the correct "AnimalFactory<A>" when I know Class<A> . I'm not even sure it's possible.
The code below gives an idea of what I'm trying to do. I'm stuck at the "getFactory(Class<A> animalClass)" and "putFactory (AnimalFactory<A> factory, Class<A> animalClass)".
Could anybody enlight me?
Thanx
It is a mistake to think you can solve any major problems just with potatoes.<br />--Douglas Adams
Ilja Preuss
author
Sheriff
Joined: Jul 11, 2001
Posts: 14112
posted
0
It's not possible without an explicit cast, as far as I know.
The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
Jeroen T Wenting
Ranch Hand
Joined: Apr 21, 2006
Posts: 1847
posted
0
it isn't. AnimalFactory<A> doesn't have an inheritance relation to Class<A> so you can't cast one to the other.
42
Garrett Rowe
Ranch Hand
Joined: Jan 17, 2006
Posts: 1295
posted
0
Maybe I don't understand fully what it is you're trying to do, but why not map the AnimalFactory<A> to the Class<A> in a Map<Class, AnimalFactory>.
Note: added a getName() method to Animal class for testing purposes
[ April 26, 2006: Message edited by: Garrett Rowe ] [ April 26, 2006: Message edited by: Garrett Rowe ]
Some problems are so complex that you have to be highly intelligent and well informed just to be undecided about them. - Laurence J. Peter
Rodrigo Alvarez
Ranch Hand
Joined: Apr 10, 2006
Posts: 75
posted
0
Hi Garrett,
Thanx a lot for your suggestion,
I think that the problem lies there :
factoryMap.get(animalClass) returns a AnimalFactory whereas we're looking for a AnimalFactory<A> , and this implies an unchecked cast
=> the compiler does not ensure that factor() returns a <A>
Actually, the more I think about it and the more I convince myself that what I'm trying to do is, as Ilja sugests, impossibe : generics mechanics all hapens in "translation time" (before compilation) but the behaviour I'm looking for is runtime stuff.
I'm probably asking too much to generics
Tanks anyway
Ilja Preuss
author
Sheriff
Joined: Jul 11, 2001
Posts: 14112
posted
0
Originally posted by Jeroen T Wenting: it isn't. AnimalFactory<A> doesn't have an inheritance relation to Class<A> so you can't cast one to the other.