Correct use for avoiding unnecessary casts with generic types (SuppressWarnings unchecked conversion)
There are similar questions out there but I didn't find any that really answers my concerns or that covers my actual implementation.
With the following example code (which reflects my actual situation)
public class MainTest {
public static void main(String[] args) {
WhateverDtoXmlParser parser = (new MainTest()).new WhateverDtoXmlParser();
// I want to do this (having to do suppressWarnings)
WhateverDto wd = par开发者_开发百科ser.getDto();
// Instead of (usage without the warning).
// I want to avoid all of this!
Dto d = parser.getDto();
WhateverDto wd2 = null;
if (d instanceof WhateverDto) { // All of this is stupid and unnecessary IMO.
wd2 = (WhateverDto) d;
}
}
abstract class AbstractDtoXmlParser {
public abstract <T extends Dto> T getDto();
}
class WhateverDtoXmlParser extends AbstractDtoXmlParser {
@SuppressWarnings("unchecked")
@Override
public WhateverDto getDto() { // instead of public Dto getDto() (to avoid instanceof + cast)
return new WhateverDto();
}
}
abstract class Dto {
// ...
}
public class WhateverDto extends Dto {
// ...
}
}
Would you consider this a correct usage even though I used a suppresswarnings?
I mean I KNOW the returned type from WhateverDtoXmlParser
will be a WhateverDto
and not just any other Dto because I coded it that way. Why can't Java check if the return type extends Dto
as I explicitly specified it with <T extends Dto
> (plus it extends an abstract class...) and accept it?
It's either I do this there, OR I have to use instanceof
s and casts everytime I use getDto()
.. ! It seems to me that my current implementation is the "best" but then why do I get such a concerning warning?
After reading the other threads it seems that there is no way to get around this warning, but should I go on with my current implementation?
Try this:
abstract class AbstractDtoXmlParser<T extends Dto> {
public abstract T getDto();
}
class WhateverDtoXmlParser extends AbstractDtoXmlParser<WhateverDto> {
@Override
public WhateverDto getDto() {
return new WhateverDto();
}
}
If you know for sure the type you are getting back is the type you are expecting, there is nothing wrong with doing an unsafe cast like this...
WhateverDto d = (WhateverDto) parser.getDto();
This still isn't the cleanest but it shouldn't give you warnings and it won't take 4 lines to write either.
精彩评论