Lau13
Lau13

Reputation: 128

How to call specific method with same name

I have these two methods:

public void method(final String param1, final Object... param2);

public void method(final String param1, final String param2, final Object... param3);

If I call the first method this way:

method(new String(), new String(), new String());

I'll get the second method because the parameters match perfectly with it. If I put the last two strings in a list I already can call the first one, but I want to know if there is another better way to do it.

Upvotes: 0

Views: 50

Answers (2)

Bohemian
Bohemian

Reputation: 425033

Pass the last parameter as an Object[]:

method("A", "B", new Object[]{"C"});

See live demo.

Upvotes: 0

Joachim Sauer
Joachim Sauer

Reputation: 308031

method(new String(), (Object) new String(), new String());

calls the first method.

This works because the second method doesn't accept Object as the second parameter, but the first one does.

It's besides the point, but I can't not point out that this should really be:

method("", (Object) "", "");

which does basically the same thing, but doesn't create pointless String objects.

Upvotes: 2

Related Questions