首页 > 解决方案 > 使用反射在类中调用构造函数

问题描述

我正在尝试使用反射在包内的类中调用构造函数。我收到异常“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()”

标签: javareflection

解决方案


这不是使用反射调用构造函数的方式。您需要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 !!
}

推荐阅读