This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Java in General and the fly likes Generics collections and reflection Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Generics collections and reflection" Watch "Generics collections and reflection" New topic

Generics collections and reflection

Franc Crosses

Joined: Nov 29, 2010
Posts: 4
Hi to all,

I have a simple class, i.e

I want to make a factory for this class, so that each collection will be instantiated to a subclass I will define:

Factory call:

TestRun tr = (TestRun) BusinessObjectFactory.create(TestRun.class);

My question is:

How Have I to instantiate the collection with the right parameter:
new HashSet<Integer>(), new ArrayList<String>(), ...

I tried with fieldObject = new HashSet<?>(); ecc
but it' not possible...

Can someone help me please?

Thanks in advance

David O'Meara

Joined: Mar 06, 2001
Posts: 13459

sorry I haven't tried compiling it, but can you try
David O'Meara

Joined: Mar 06, 2001
Posts: 13459

and now I see I have answered the wrong question. One sec, digging deeper...
David O'Meara

Joined: Mar 06, 2001
Posts: 13459

I have asked this question before but have not received a answer yet.
If you have ClassA extends GenericClass<ClassB> you can sometimes get the type of ClassB from ClassA using:
((ParameterizedType) fieldClass.getGenericSuperclass()).getActualTypeArguments()[0]

But the same does not work with plain old class of type GenericClass<ClassB>
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 37945
And welcome to the Ranch
David O'Meara

Joined: Mar 06, 2001
Posts: 13459

like this
I agree. Here's the link:
subject: Generics collections and reflection
Similar Threads
Duplicates in HashSet
Validation Error: Value is not valid
java.lang.Reflection throwing error when using (String)field.get(new String());
how come generis type information at runtime/reflection ?
List Vs Set