如何在 Java 中拥有每个平台 类?

How to have per-platform classes in Java?

我正在 Java 中编写串行接口。它使用 JNA 访问底层原生 API。我已经定义了一个包含经典方法(打开、读取、写入、关闭...)的 SerialPort 接口:

public interface SerialPort {
    void open(String portName) throws IOException;
    void close() throws IOException;
    void write(byte[] data) throws IOException;
    byte[] read(int bytes) throws IOException;
    byte[] read(int bytes, int timeout) throws IOException;
    void setConfig(SerialConfig config) throws Exception;
    SerialConfig getConfig();
}

现在,我想要基于 运行 平台的实现。这样做的好方法是什么?我必须在运行时加载 类 吗?

如果我创建两个 类 实现此接口(SerialPortUnixSerialPortWin32)。我想要一个基于平台 return 一个或另一个的功能。

我怎样才能正确地做到这一点?

谢谢,

为不同的平台实施不同的 SerialPort 实例。假设我们有 SerialPort 实现:serialPortWindows 用于 Windows,serialPortLinux 用于 Linux

然后使用System.getProperty("os.name");调用确定平台并使用相关class。

如果您的应用在 windows 或 linux 上运行,请尝试以下示例:

String os = System.getProperty("os.name").toLowerCase();
SerialPort serialPortImpl;
if (os.substring("windows") != -1) {
   // use windows serial port class
   serialPortImpl = serialPortWindows; 
} else {
   // use linux serial port class
   serialPortImpl = serialPortLinux;     
}

// now use serialPortImpl, it contains relevant implementation
// according to the current operating system