简体   繁体   English

消除未经检查的警告:将String强制转换为T

[英]Eliminate unchecked warning: cast String to T

Following method which returns a list with a dynamic type parameter: 以下方法返回带有动态类型参数的列表:

public List<T> getDataList() throws SQLException {
  List<T> l = new ArrayList<T>();
  l.add((T) "Test");
  return l;
}

This gives me an unchecked cast warning. 这给了我一个未经检查的强制警告。

If I change the code to: 如果我将代码更改为:

public List<T> getDataList() throws SQLException {
  List<String> l = new ArrayList<String>();
  l.add("Test");
  (List<T>) return l;
}

it is nearly the same. 它几乎是相同的。 I get a unchecked cast warning. 我收到未经检查的演员表警告。

Question: 题:

Is it possible to eliminate this unchecked warning without loosing flexibility of getDataList method? 是否可以消除这种未经检查的警告而又不丧失getDataList方法的灵活性?

public MyClass implements DataListInterface<String>

I think the warning is very appropriate in this situation. 我认为警告在这种情况下非常合适。

Consider your method containing the generic type, its really not so generic since it would only work for a type argument of String . 考虑一下包含通用类型的方法,实际上它不是那么通用,因为它仅适用于String的类型参数。

public class Generic<T> {

    public List<T> getDataList() throws SQLException {
          List<T> l = new ArrayList<T>();
          l.add((T) "Test");
          return l;
        }
}

If I were to execute: 如果我要执行:

   Generic<Integer> generic = new Generic<Integer>();

A ClassCastException will be thrown appropriately since the code will attempt to cast an Integer to a String . 由于代码将尝试将Integer转换为String将适当地抛出ClassCastException

Firstly it is highly risky doing any of the above. 首先,进行上述任何一项工作都具有很高的风险。

Doing l.add((T) "Test"); l.add((T) "Test"); will not throw ClassCastException iff the type T is String . 如果类型TString则不会抛出ClassCastException In that case, once could directly just return List<String> because for anything else an Exception will be thrown. 在那种情况下,一次可以直接返回List<String>因为对于其他任何事情都将引发Exception。

And if you are trying to protect the warning by @SuppressWarning then it is only a time-off for a bomb that will occur later. 而且,如果您尝试通过@SuppressWarning保护警告,则只是稍后发生炸弹而已。 Warnings are thrown for a reason. 发出警告是有原因的。

You can solve it by 你可以通过解决

class Whatever implements SomeInterface<String>

Try using it like this. 尝试像这样使用它。 (Modified your second approach) (修改了第二种方法)

public  <T> List<T> getDataList() throws SQLException {
          List<String> l = new ArrayList<String>();
          l.add("Test");
           return (List<T>)l;
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM