Arashsoft Arashsoft - 14 days ago 5
Java Question

Compiler error in method overloading with varags argument in Java

I have two functions like this:

String getMessage(String code, Object... objects);
String getMessage(Locale locale, String code, Object... objects);


And I try to call the first function without varags argument:

myClass.getMessage("online.order");


I get this compiler error:


Error: java: incompatible types: java.lang.String cannot be converted
to java.util.Locale


It tries to use the second function and I do not understand why?

Update: Context of the code

This is the interface that define those two functions:

public interface MyMessageProvider {
String getMessage(String code, Object... objects);
String getMessage(Locale locale, String code, Object... objects);
}


This is the actual class that implements that interface and also extends Spring
ReloadableResourceBundleMessageSource


public class CustomMessageSource extends ReloadableResourceBundleMessageSource implements MyMessageProvider {
public static final String BEAN_NAME = "messageSource";

public static CustomMessageSource getInstance() {
return (CustomMessageSource) SpringApplicationContext.getBean(BEAN_NAME);
}

@Override
public String getMessage(String code, Object[] objects) {
return getMessage(getCurrentLocale(), code, objects);
}

@Override
public String getMessage(Locale locale, String code, Object... objects) {
return getMessage(code, objects, code, locale);
}
}


And I call getMessage in a class like this:

public class MyService {
@Autowired
private CustomMessageSource messageSource;

public String createSomeMessage(){
messageSource.getMessage("online.order");
}

}


I can solve the issue by adding
String getMessage(String code)
to the interface/implementation. The compile error does not makes sence to me same as you guys. But, I am getting the compile error!

Answer
public String getMessage(String code, Object[] objects)

The signature of the overridden method contains an Object[] array as the second parameter. That's not the same as a varargs parameter (Object...). To invoke this method, you have to pass an array or null there:

instance.getMessage("code", new Object[]{});
instance.getMessage("code", null);
Comments