File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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 Java 8 in Action this week in the Java 8 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: 36575
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
how come generis type information at runtime/reflection ?
Duplicates in HashSet
List Vs Set
java.lang.Reflection throwing error when using (String)field.get(new String());
Validation Error: Value is not valid