Generic methods returning dynamic object types

前端 未结 3 1129
情书的邮戳
情书的邮戳 2021-01-30 22:54

Possibly a question which has been asked before, but as usual the second you mention the word generic you get a thousand answers explaining type erasure. I went through that ph

3条回答
  •  旧时难觅i
    2021-01-30 23:14

    You could try type tokens:

    public  T getValue(Class cls) {
        if (valVal == null) return null;
        else {
            if (cls.isInstance(valVal)) return cls.cast(valVal);
            return null;
        }
    }
    

    Note, that this does not do any conversion (i.e., you cannot use this method to extract a Double, if valVal is an instance of Float or Integer).

    You should get, btw., a compiler warning about your definition of getValVal. This is, because the cast cannot be checked at run-time (Java generics work by "erasure", which essentially means, that the generic type parameters are forgotten after compilation), so the generated code is more like:

    public Object getValVal() {
        return valVal;
    }
    

提交回复
热议问题