簡體   English   中英

正確使用避免不必要的泛型類型轉換(SuppressWarnings unchecked conversion)

[英]Correct use for avoiding unnecessary casts with generic types (SuppressWarnings unchecked conversion)

那里有類似的問題,但我沒有找到任何真正回答我的問題或涵蓋我的實際實施的問題。

用下面的示例代碼(反映了我的實際情況)

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 = parser.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 {
        // ...
    }
}

即使我使用了抑制警告,您是否認為這是正確的用法? 我的意思是我知道 WhatDtoXmlParser返回的類型將是一個WhateverDtoXmlParser而不僅僅是任何其他WhateverDto ,因為我是這樣編碼的 為什么 Java 不能檢查返回類型是否extends Dto ,因為我使用<T extends Dto > 明確指定它(加上它擴展了抽象 class...)並接受它?

要么我在那里這樣做,要么我每次使用getDto()時都必須使用instanceof和演員表? 在我看來,我當前的實現是“最好的”,但是為什么我會收到這樣一個令人擔憂的警告呢?

在閱讀了其他線程之后,似乎沒有辦法繞過這個警告,但我應該用我當前的實現 go 嗎?

嘗試這個:

abstract class AbstractDtoXmlParser<T extends Dto> {
    public abstract T getDto();
}

class WhateverDtoXmlParser extends AbstractDtoXmlParser<WhateverDto> {

    @Override
    public WhateverDto getDto() {
        return new WhateverDto();
    }
}

如果您確定要返回的類型是您期望的類型,那么進行這樣的不安全強制轉換沒有任何問題...

WhateverDto d = (WhateverDto) parser.getDto();

這仍然不是最干凈的,但它不應該給你警告,也不需要 4 行來寫。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM