Java – how to select overloaded methods by parameter types?

I tried to overload my method based on the parameter type:

Fielderror extends to objecterror

private String getMessage(final FieldError fieldError) {
    return String.format("%s %s",fieldError.getField(),fieldError.getDefaultMessage());
}

private String getMessage(final ObjectError objectError) {
    return objectError.getDefaultMessage();
}

Now, if I have a list < objecterror > and call the above method for the elements of the list, GetMessage (final objecterror objecterror) will always be called regardless of the type of the elements on the list (objecterror or fielderror)

List<ObjectError> errors;
getMessage(errors.get(0));

Why? If it just works, is there a chance not to use if and instanceof?

Solution

When only compile time types are known, method overload resolution is performed at compile time Therefore, the compile - time type of the parameters passed to the method call determines which overloaded methods are selected

Because you want to pass the element of list < objecterror > For method calls, always select string GetMessage (final objecterror objecterror), and the runtime types of the instances stored in the list are the same

One way to solve the problem is to move the GetMessage () method to the objecterror class and override it in the fielderror subclass

replace

getMessage(errors.get(0))

Will you call

errors.get(0).getMessage()

This will work because method overrides are resolved at run time

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>