這是this question about java private constructors的後續操作。Java:訪問帶有類型參數的私有構造函數
假設我有以下類:
我將如何構建一個new Foo("hello")
使用反射?
ANSWER
基於jtahlborn's answer,以下工作:
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.lang.NoSuchMethodException:my.package.path.Foo(java.lang.Object中) \t在java.lang.Class.getConstructor0(Class.java:2892) \t在java.lang.Class.getDeclaredConstructor(Class.java:2058) \t在ProductCatalogAgentTest.testConnect(ProductCatalogAgentTest.java:461) \t在sun.reflect.NativeMethodAccessorImpl.invoke0(本機方法) –
2015-09-22 23:13:02