generics - Initializing variable. I don't know their type [java] -



generics - Initializing variable. I don't know their type [java] -

class pair<u,v>{ u first; v second; public pair() { first = new u(); //error sec = new v(); //error } public pair(u f,v s){ first = f; sec = s; } }

required: class found: type parameter

is possible initialize first/second (without-arguments) constructor of u/v type other way?

java not allow because of type erasure. can specify constructor arguments of type class<u> , class<v>, pass in concrete class types of given type parameters (i.e., integer.class , string.class <integer> , <string>).

it possible extract type using bytecode-level reflection, quite complicated, , doesn't work in situations. if scroll downwards on this article, can find illustration makes possible. i've pasted below convenience.

static public type gettype(final class<?> klass, final int pos) { // obtain anonymous, if any, class 'this' instance final type superclass = klass.getgenericsuperclass(); // test if anonymous class employed during phone call if ( !(superclass instanceof class) ) { throw new runtimeexception("this instance should belong anonymous class"); } // obtain rtti of generic parameters final type[] types = ((parameterizedtype) superclass).getactualtypearguments(); // test if plenty generic parameters passed if ( pos < types.length ) { throw runtimeexception(string.format("could not find generic parameter #%d because %d parameters passed", pos, types.length)); } // homecoming type descriptor of requested generic parameter homecoming types[pos]; }

edit: reply comment:

class pair<u,v>{ u first; v second; public pair(class<u> cu, class<v> cv) { seek { first = cu.newinstance(); sec = cv.newinstance(); } grab (exception e) { throw new illegalargumentexception(e); } } public pair(u f,v s){ first = f; sec = s; } }

java generics

Comments

Popular posts from this blog

iphone - Dismissing a UIAlertView -

intellij idea - Update external libraries with intelij and java -

javascript - send data from a new window to previous window in php -