Suppose I have the following class:
class Foo
{
private T arg;
private Foo(T t) {
// private!
this.arg = t;
}
@Override
public String toString() {
return "My argument is: " + arg;
}
}
How would I construct a 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 constructor;
constructor = Foo.class.getDeclaredConstructor(Object.class);
constructor.setAccessible(true);
Foo foo = constructor.newInstance("arg1");
System.out.println(foo);
}
}
解决方案
you would need to get the class, find the constructor which takes a single argument with the lower bound of T (in this case Object), force the constructor to be accessible (using the setAccessible method), and finally invoke it with the desired argument.