Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

generic factory ?

 
Rodrigo Alvarez
Ranch Hand
Posts: 75
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,

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


 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's not possible without an explicit cast, as far as I know.
 
Jeroen T Wenting
Ranch Hand
Posts: 1847
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
it isn't.
AnimalFactory<A> doesn't have an inheritance relation to Class<A> so you can't cast one to the other.
 
Garrett Rowe
Ranch Hand
Posts: 1296
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Rodrigo Alvarez
Ranch Hand
Posts: 75
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.


I think you misunderstood the question.
 
Tony Morris
Ranch Hand
Posts: 1608
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
See if this helps: http://jtiger.org/javadoc/org/jtiger/assertion/ObjectFactory.html

As a note, you don't need to pass a Class instance, since the parameterised type can be inferred by the return value.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic