I was wondering if it is possible to create a construtor function:
public <C, T> C newInstance(Class<C> constructor_class,
Class<T> type,
Object...parameters){
// create a new Instance with the generic type and the paramters
//so basicly like this, but with generics and parameters
return constructor_class.newInstance();
}
You basically can't. Your example is broken - what is
type
supposed to represent?Let's say you want to dynamically create a
HashMap<String, Integer>
. This would require that you pass inHashMap.class
,String.class
, andInteger.class
, but we run into a TON of problems right off the bat:Furthermore,
Class
cannot be used to convey generics args. What if I wanted aHashMap<List<String>, Integer>
instead?List<String>
does not exist as a class literal, sojava.lang.Class<T>
cannot be used here. There are also class objects (specifically,int.class
) that aren't legal in generics. So, we have?
,? super Foo
,A, B extends A, C extends A & Serializable
,List<String>
all as examples of things that can go in<>
but which cannot be ajava.lang.Class
reference, andint.class
that is a legal class ref but which cannot go in<>
. You can't put a square peg in a round hole. Let alone the fact that even if you could, it would do literally absolutely nothing whatsoever (see point #3: This is useless - most generics, and definitely the generics you'd use here, affect compilation and cease to exist afterwards).There are crazy hacks in this space (super type tokens, for example), but if you do not fully understand how generics work under the hood, there is 0.00001% or less chance you will be able to use such hacks usefully, so don't bother until then. And asking this question, especially with that pseudocode, strongly suggests you don't understand enough of it yet.