簡體   English   中英

使用反射在類內調用構造函數

[英]Invoke Constructor inside a class using 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()”

那不是通過反射調用構造函數的方式。 您需要直接從Constructor對象調用newInstance(...)

給定此類:

/* 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[]數組並選擇所需的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 !!
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM