Take the 2-minute tour ×

Guess you have a class with some c-tors:

public Foo(int i, String s);
public Foo(float fl, String s);
public Foo(String s, Bar b, boolean f);

Now, when you have the following fn:

public Foo doSomething(Object… args)
    /*… do something before … */
    Foo foo = new Foo( ?!? );
    /*… do something after … */
    return foo;

What should one to to call the correct c-tor? Is there a way to translate args back into the ...-form?

share|improve this question
If you feel the need to do this it's time for a redesign. Just my opinion. –  Ingo Mar 23 '11 at 16:48
The main problem is: i (better:java!) cant do something like class foo<T extends bar> { T = new T(x,y,z); } so 'id like to provide a way for derived classes to construct the T. –  rhavin Mar 23 '11 at 16:58

4 Answers 4

up vote 0 down vote accepted

You can, of course check the number and type of the arguments and dispatch accordingly. But note my comment above.

share|improve this answer
Seems like your comment remains the only chance… –  rhavin Mar 24 '11 at 10:12

No - after all, there could be any references in there, including null references.

You'd have to check the values you've actually been given against the parameter types for the constructor signatures.

I'd regard this as a sign that you probably shouldn't be using varargs in this situation. You could always overload the method with the same signatures as the constructors, and call common helper methods for the before/after parts... or if the time of the constructor call doesn't matter, do it all in a common method, except the construction:

public void doSomething(int i, String s)
    doSomethingHelper(new Foo(i, s));
share|improve this answer

Apart from inspecting the concrete type of each element in args, casting them down manually, then invoking the proper constructor via reflection, there isn't much you can do. (And that would be ugly like hell...) The compiler needs to bind constructor calls statically, but you only get to know the concrete parameters at runtime.

An alternative would be to provide a constructor with varargs parameter, but this just delegates the problem one level lower. @Jon's suggestion of getting rid of the varargs altogether is better.

share|improve this answer
It is ugly like hell, i have aleady tried that ;-/ I always end up mimicing behaviour the compiler should do for me. –  rhavin Mar 23 '11 at 17:08

Note that Object... is really just syntactic sugar for Object[]. So you have the same options here as you would if your parameter type was Object[].

share|improve this answer
Thats part of the problem: Object[] may be run-time variable. I'd wish there would be something that is just allowed to be compile-time-variable. So the Compiler sees "String, boolean, int" and links the appropriate fn. –  rhavin Mar 23 '11 at 17:06
You might be better off passing the Foo itself into doSomething(). –  kprevas Mar 23 '11 at 19:06

Your Answer


