reflection - Java: accessing private constructor with type parameters -


this followup this question java private constructors.

suppose have following class:

class foo<t> {     private t arg;     private foo(t t) {         // private!         this.arg = t;     }         @override     public string tostring() {         return "my argument is: " + arg;     }    } 

how construct new foo("hello") using reflection?

answer

based on jtahlborn's answer, following works:

public class example {     public static void main(final string[] args) throws exception {         constructor<foo> constructor;         constructor = foo.class.getdeclaredconstructor(object.class);         constructor.setaccessible(true);         foo<string> foo = constructor.newinstance("arg1");         system.out.println(foo);     }    } 

you need class, find constructor takes single argument lower bound of t (in case object), force constructor accessible (using setaccessible method), , invoke desired argument.


Comments

Popular posts from this blog

php - What is the difference between $_SERVER['PATH_INFO'] and $_SERVER['ORIG_PATH_INFO']? -

fortran - Function return type mismatch -

queue - mq_receive: message too long -