Zugriff auf parametrisierten Konstruktor mit Reflection API. Ich habe versucht, es mit der folgenden Klasse zu tun, aber es wirft einen Fehler auf.Parametrisierter privater Konstruktor mit Reflection
//Primary class
package com.deepak;
public class A {
private String name;
private A(String name) {
this.name = name;
}
}
//Exact class
class MethodCall {
Class first = Class.forName("com.deepak.A");
Constructor constructor1 = first.getDeclaredConstructor();
constructor1.setAccessible(true);
A a= (A) constructor1.newInstance("deepak");
System.out.println(a);
}
Fehlermeldung:
Exception in thread "main" java.lang.NoSuchMethodException: com.deepak.A.<init>()
at java.lang.Class.getConstructor0(Class.java:3082)
at java.lang.Class.getDeclaredConstructor(Class.java:2178)
at com.deepak.MethodCall.main(MethodCall.java:44)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
Randbemerkung: Sie sollten mit rohen Typen vermeiden. –