开发者

Java varargs: a way to get back to the ...-form?

开发者 https://www.devze.com 2023-02-19 01:43 出处:网络
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);

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?


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


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.


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


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[].

0

精彩评论

暂无评论...
验证码 换一张
取 消