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
Post a Comment