枚举警告

时间:2011-11-15 08:33:35

标签: java eclipse enumeration rxtx

我想用Eclipse执行this RxTx web site提供的示例代码  :

import gnu.io.*;
public class SerialPortLister {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        listPorts();
    }
    private static void listPorts()
    {
        java.util.Enumeration<CommPortIdentifier> portEnum = CommPortIdentifier.getPortIdentifiers();  // this line has the warning
        while ( portEnum.hasMoreElements() ) 
        {
            CommPortIdentifier portIdentifier = portEnum.nextElement();
            System.out.println(portIdentifier.getName()  +  " - " +  getPortTypeName(portIdentifier.getPortType()) );
        }        
    }
    private static String getPortTypeName ( int portType )
    {
        switch ( portType )
        {
            case CommPortIdentifier.PORT_I2C:
                return "I2C";
            case CommPortIdentifier.PORT_PARALLEL:
                return "Parallel";
            case CommPortIdentifier.PORT_RAW:
                return "Raw";
            case CommPortIdentifier.PORT_RS485:
                return "RS485";
            case CommPortIdentifier.PORT_SERIAL:
                return "Serial";
            default:
                return "unknown type";
        }
    }
}

第13行有警告:Type safety: The expression of type Enumeration needs unchecked conversion to conform to Enumeration<CommPortIdentifier>

这个警告意味着什么以及如何解决它?

2 个答案:

答案 0 :(得分:6)

在弗拉迪斯拉夫·鲍尔的第二个要点上详细说明,你可以初始化portEnum,如:

Enumeration<?> portEnum = CommPortIdentifier.getPortIdentifiers();

然后在while结构中,您可以将每个元素转换为您需要的类型,在本例中为CommPortIdentifier:

 CommPortIdentifier portIdentifier = (CommPortIdentifier) portEnum.nextElement();

投射每个元素将使警告消失。但是我们必须小心并确保portEnum始终包含我们期望的CommPortIdentifier类型的元素。

答案 1 :(得分:0)

我不知道getPortIdentifiers方法的代码,但在当前情况下:

  • 解决方案是在报告警告的方法前面添加以下注释:@SuppressWarnings(“unchecked”)

  • 您还可以将类型转换为未知类型。示例:枚举portEnum = CommPortIdentifier.getPortIdentifiers();

相关问题