简体   繁体   中英

Invoke Constructor inside a class using Reflection

I am trying to invoke a constructor in a class within a package using reflection. I am getting exception "java.lang.NoSuchMethodException:"

Below is the code.

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);
    }
}

Expected result to invoke demo7 constructor inside the demo7 class and print value dfdfd. The exception is thrown "java.lang.NoSuchMethodException: org.la4j.demo7.org.la4j.demo7()"

That's not how constructors are invoked with reflection. You need to invoke newInstance(...) directly from the Constructor object.

Given this class:

/* 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); 
    }
}

You need to get the constructor you want either by specifying the parameter types to getConstructor(...) , or as you have done, getting the array of Constructor[] and picking the one you want (much harder when you have more than one 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 !!
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM