使用反射

时间:2019-09-09 21:36:03

标签: java reflection

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

1 个答案:

答案 0 :(得分:0)

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