JodaOrg / joda-convert

Java library to enable conversion to and from standard string formats.

Home Page:http://www.joda.org/joda-convert/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Why does FromStringConverter.convertFromString have a Class param?

opened this issue · comments

This is not a bug, but a general design question.

Why does the convertFromString take a Class<? extends T> parameter?

It's used in two places:

  • EnumStringConverter -- When would the specified cls differ from the converter's effectiveType?
  • MethodsStringConverter -- When would a caller want to specify a different cls param?

Thanks, I couldn't find an explanation in the docs or in the source.

The parameter is used to make generics work - to have a return type of T you have to pass something in that is related, Class<T> in this case.

For the "effective type" and why it differs, see "effective type" in the user guide.

I'm still a little confused. I don't see when a FromStringConverter<T> or its caller would need to use the specified cls type instead of its instance's type <T>.

Can you give an example? (I mentioned MethodsStringConverter and EnumStringConverter because those are the only instances that use the specified cls type and I thought they could be implemented without it. All other implementations ignore the cls parameter.)

Edit: I see now that it's used to throw the ClassCastException immediately when the caller attempts to convert to a subclass (tested in TestStringConvert.test_convert_annotationSuperFactorySubViaSub2). Without it, the exception would only be thrown if the caller attempted to assign the result.