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?
It is a mistake to think you can solve any major problems just with potatoes.<br />--Douglas Adams
Joined: Jul 11, 2001
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
Joined: Apr 21, 2006
it isn't. AnimalFactory<A> doesn't have an inheritance relation to Class<A> so you can't cast one to the other.
Joined: Jan 17, 2006
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
Joined: Apr 10, 2006
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
Joined: Jul 11, 2001
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.