代码之家  ›  专栏  ›  技术社区  ›  Codi

java@SuppressWarnings(“unchecked”)的语法,继承泛型类型[重复]

  •  3
  • Codi  · 技术社区  · 7 年前

    我有如下定义的类,其中包含一些方法

    public abstract class Pojo<T extends Pojo<T, U>, U extends Phase<U>> {
        ...
        public T updatePhase(U phase) {
            this.previousPhase = this.phase;
            this.phase = phase;
            return getThis();
        }
    
        public U getPreviousPhase(U phase) {
            return this.previousPhase;
        }
    
        @SuppressWarnings("unchecked")
        public T getThis() {
            return (T) this;
        }
    
        public Map<String, String> getMap() {
            return this.map;
        }
    }
    
    public interface Phase<U extends Phase<U>> { ... }
    

    稍后在我的代码中,我将尝试执行以下操作:

    Pojo pojo = someService.get(id); // This can't be a definite type since I get this by deserializing a string
    Phase ap = pojo.getPreviousPhase();
    pojo.updatePhase(ap); // I get the unchecked warning here (case 1)
    Map<String, String> myMap = pojo.getMap(); // I get the unchecked warning here (case 2)
    myMap.put("1", "2"); // This obviously works
    

    案例1:未选中的调用 updatePhase(U) 作为原始类型的成员。
    我理解为什么这会发出警告。如何使用 @SuppressWarnings("unchecked") 这种情况下的注释(语法方面)?如果我把它合并到一个语句中,它将如何使用 pojo.updatePhase(pojo.getPreviousPhase)

    情况2:未经检查的转换,必需 Map<String,String> 建立 Map
    为什么会发出警告?我返回一个确定类型 Map<String, String> 所以它不应该在意。。。类似地,我如何应用 @SuppressWarnings 注释在这里?类似地,在单行语句中我该如何做呢 pojo.getMap().put("1", "2")

    注意:我确实在代码中确保所有这些类型转换都是正确的,并且不会在运行时导致强制转换错误。

    1 回复  |  直到 7 年前
        1
  •  2
  •   Sean Van Gorder    7 年前

    使用原始类型禁用泛型类型检查是个坏主意。对于第一个问题,与其试图将未知类型的对象强制放入未知类型的泛型方法参数中,不如告诉 Pojo 要在内部传递字段值,请执行以下操作:

    public T updateFromPrevious() {
        return updatePhase(getPreviousPhase());
    }
    

    Pojo<?,?> pojo = someService.get(id);
    pojo.updateFromPrevious();
    Map<String, String> myMap = pojo.getMap();
    myMap.put("1", "2");