This is a continuation of this question about private java constructors .
Suppose I have the 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 would I build new Foo("hello") using reflection?
ANSWER
Based on jtahlborn's answer , the 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); } }
java reflection private constructor
dsg Apr 12 2018-11-11T00: 00Z
source share