java - 使用反射在类中调用构造函数
问题描述
我正在尝试使用反射在包内的类中调用构造函数。我收到异常“java.lang.NoSuchMethodException:”
下面是代码。
public class constructor_invoke {
public static void main(String args[]) throws ClassNotFoundException, NoSuchMethodException
{
Method m = null;
Class c = Class.forName("org.la4j.demo7");
Constructor[] cons = null;
cons=c.getConstructors();
m = c.getMethod(cons[0].getName());
m.invoke(c.newInstance());
}
}
demo7.java
public class demo7 {
String a="df";
public void demo7()
{
String getval2=a+"dfd";
System.out.println(getval2);
}
}
在 demo7 类中调用 demo7 构造函数并打印值 dfdfd 的预期结果。抛出异常“java.lang.NoSuchMethodException: org.la4j.demo7.org.la4j.demo7()”
解决方案
这不是使用反射调用构造函数的方式。您需要newInstance(...)
直接从Constructor
对象调用。
给定这个类:
/* Test class with 2 constructors */
public static class Test1{
public Test1() {
System.out.println("Empty constructor");
}
public Test1(String text) {
System.out.println("String constructor: " + text);
}
}
您需要通过指定参数类型来获得所需的构造函数getConstructor(...)
,或者像您所做的那样,获取数组Constructor[]
并选择您想要的构造函数(当您有多个构造函数时会更难)。
public static void main(String[] args) throws Exception {
Object result = null;
// Get the class by name:
Class<?> c = Class.forName("testjavaapp.Main$Test1");
// Get its 2 different constructors:
Constructor<?> conEmpty = c.getConstructor(); // Empty constructor
Constructor<?> conString = c.getConstructor(String.class); // Constructor with string param
// Now invoke the constructors:
result = conEmpty.newInstance(); // prints "Empty constructor"
result = conString.newInstance("Hello"); // prints "String constructor: Hello"
// The empty constructor (but not others) can also be invoked
// directly from the Class object.
// --NOTE: This method has been marked for deprecation since Java 9+
result = c.newInstance(); // prints "Empty constructor"
result = c.newInstance("Hello"); // !! Compilation Error !!
}
推荐阅读
- kubernetes - 如何根据嵌套值的存在有条件地渲染 helm 模板
- angular - 在 ANGULAR 中发布数组参数的正确方法是什么?
- javascript - appendChild 到旁边或右边
- android - PackageManager 没有返回带有 targetSdkVersion 30 的正确包
- python - 如何使用 Python 将 CSV 文件转换为 XML 格式
- javascript - D3.js 是否可以使用嵌套数据在每个点上绘制圆圈?
- javascript - 我的 JSON 输出仅打印 [object] 而不是值
- java - 如何在 Tomcat 8 中将多个展开的 webapps($CATALINA_BASE/webapps 之外)设置为 ROOT?
- python - Cannot get the emulator running for my Android App using beeware (newbie)
- java - Writing a program to check password for certain things