Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to convert Class to Instance Object

take a look at my code....

    Class<?> c = Class.forName("PerformanceInvokeService");

    Method m = c.getDeclaredMethod("monthlyTestCal", new Class[] {
            String.class, Date.class });
    Object ret = m.invoke("PerformanceInvokeService", new Object[] {
            "some string", new Date() });
    System.out.println(ret);

i execute this and its thrown an exception

java.lang.IllegalArgumentException: object is not an instance of declaring class

i think, because i don't create an instance of c (likes...new PerformanceInvokeService()) and i don't know how to create it

somebody help?

sorry for my english...

thanks

like image 974
Poringe Avatar asked Oct 23 '25 15:10

Poringe


2 Answers

If PerformanceInvokeService has an accessible default constructor, you can create a new instance using:

Object instance = c.newInstance();

You can then pass that to the method invocation:

Object ret = m.invoke(instance, new Object[] { "some string", new Date() });

If there is no accessible default constructor, then you'll have to find a constructor that you can use by using reflection.

like image 103
Ted Hopp Avatar answered Oct 26 '25 05:10

Ted Hopp


Class has a newInstance() method that you can call to create an instance of the class using its default constructor. Or, you can call getConstructor() or getConstructors() to find a constructor that takes the right kind of arguments, and then call newInstance() on the Constructor object, passing the construction arguments.

like image 45
Wyzard Avatar answered Oct 26 '25 03:10

Wyzard



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!