如何使用Reflection API访问参数化构造函数。我一直试图用下面的一组类来做它,但它会引发一些错误。
//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);
}
错误讯息:
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)
答案 0 :(得分:3)
此Exception
表示在relection
中找不到constructor
而没有param
,因为班级A
只有一个constructor
接受String
param
。
所以你应getConstructor
使用constructor
parameter
课程,例如:
Constructor constructor1 = first.getConstructor(String.class);
答案 1 :(得分:0)
您可以使用以下代码来获取所需内容:
public static void main(String[] args) throws Exception {
Class first = Class.forName("com.deepak.A");
Constructor[] declaredConstructors = first.getDeclaredConstructors();
Constructor constructor1 = declaredConstructors[0];
constructor1.setAccessible(true);
A a= (A) constructor1.newInstance("deepak");
System.out.println(a);
}