-1

I am trying to call newInstance method of java.lang.reflect.Constructor class in order to create an object based on constructor received.
I need to generate dynamic call in class B

class A
{
    void method()
    {
        ABC abc = new ABC(arg1,arg2);
        Constructor c = Class.forName("someClass").getConstructor(ABC.class);
        Object o = B.getObject(c,abc);
        Object 
        //do something
    }

}
class B
{
    public static Object getObject(Constructor c, Object... args)
    {
        //how to create dynamic call here???
        c.newInstance(args[0],args[1],...,args[args.length-1]);
    }
}
class someClass
{
    someClass(ABC abc)
    {
        //do something
    }
    someClass(ABC abc, int a)
    {
        //do something
    }
}

I cannot modify someClass whatsoever. (Actually someClass is just an example. I am calling 10-15 different calsses, so modifying is not an option. Plus, I need to make class B generic)

1
  • Here's a simple question/answer that shows how to invoke a method using reflection. Commented Jun 6, 2014 at 8:36

1 Answer 1

1

You can pass an array as a ... parameter:

c.newInstance(args)
Sign up to request clarification or add additional context in comments.

7 Comments

this won't work since newInstance method assumes that the constructor has only 1 argument viz. Object[]
@AbhishekBhatia: You sure? It seems to work when I try it; I'll try some more and either show you a demonstration it works or find out you're right.
It was giving IllegalArgumentException when I tried. Do show me a demo if it works for you
I hope you realize that my issue is not that I cannot set array as a parameter rather I need to send all array elements as different arguments
@AbhishekBhatia: Then you wrap it in another array - c.newInstance(new Object[] {array}) - or cast it to Object so the compiler wraps it in another array for you - c.newInstance((Object) array).
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.