【问题标题】:Invoke Constructor inside a class using Reflection使用反射在类中调用构造函数
【发布时间】:2020-01-11 15:53:42
【问题描述】:

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

【问题讨论】:

    标签: java reflection


    【解决方案1】:

    这不是使用反射调用构造函数的方式。您需要直接从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[] 的数组并选择您想要的构造函数(当您有多个时会更难)构造函数)。

    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 !!
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多