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

Abhishek Bhatia
  • 716
  • 9
  • 26
  • Here's a [simple question/answer](http://stackoverflow.com/a/2407242/778118) that shows how to invoke a method using reflection. – jahroy Jun 06 '14 at 08:36

1 Answers1

1

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

c.newInstance(args)
user2357112
  • 260,549
  • 28
  • 431
  • 505
  • this won't work since `newInstance` method assumes that the constructor has only 1 argument viz. `Object[]` – Abhishek Bhatia Jun 06 '14 at 08:20
  • @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. – user2357112 Jun 06 '14 at 08:24
  • It was giving `IllegalArgumentException` when I tried. Do show me a demo if it works for you – Abhishek Bhatia Jun 06 '14 at 08:26
  • 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 – Abhishek Bhatia Jun 06 '14 at 08:31
  • @AbhishekBhatia: Take a look at the following: http://ideone.com/lDCHob – user2357112 Jun 06 '14 at 08:32
  • It really works, but I am now puzzled : what if the constructor itself needs an Object[] ? see: http://ideone.com/eVuqLy – Abhishek Bhatia Jun 06 '14 at 08:38
  • 1
    @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)`. – user2357112 Jun 06 '14 at 08:40