lundi 9 septembre 2019

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()"





Aucun commentaire:

Enregistrer un commentaire