枚举警告

phe*_*mix 1 java eclipse enumeration rxtx

我想用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";
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

eva*_*asa 6

详细说明Vladislav Bauer的第二个要点,你可以初始化portEnum,如:

Enumeration<?> portEnum = CommPortIdentifier.getPortIdentifiers();
Run Code Online (Sandbox Code Playgroud)

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

 CommPortIdentifier portIdentifier = (CommPortIdentifier) portEnum.nextElement();
Run Code Online (Sandbox Code Playgroud)

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