1

我想用 Eclipse 执行这个 RxTx 网站提供的示例代码 :

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>

这个警告是什么意思以及如何解决它?

4

2 回答 2

7

详细阐述 Vladislav Bauer 的第二个要点,您可以像这样初始化 portEnum:

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

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

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

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

于 2015-07-27T15:59:22.257 回答
0

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

  • 解决方法是在上报警告的方法前添加如下注解:@SuppressWarnings("unchecked")

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

于 2011-11-15T08:42:13.373 回答