java - 如何为类似 ResultSet 的 API 实现通用包装器?

标签 java generics reflection

我有一个第三方RPC-API,它提供了类似于java.sql.ResultSet的接口(interface)(用于读取值)和 java.sql.PreparedStatement (用于写入值)。假设它看起来像这样:

public interface RemoteDeviceProxy {
    public void setBoolean(Boolean value);
    public void setInteger(Integer value);
    // ...

    public Boolean getBoolean();
    public Integer getInteger();
    // ...
}

我想为此 API 编写一个包装器,它使用泛型来创建特定类型的实例:

public class <T> RemoteVariable {
    private final RemoteDeviceProxy wrappedDevice;

    public RemoteVariable(RemoteDeviceProxy wrappedDevice) {
        this.wrappedDevice = wrappedDevice;
    }

    public T get() {
        // should call wrappedDevice.getBoolean() if T is Boolean, etc.
        // how to implement?
    }

    public void set(T newValue) {
        // should call wrappedDevice.setBoolean(newValue) if T is Boolean, etc.
        // implement using instanceof
    }
}

如何在我的通用包装器中实现 getter?我找到了this answer这深入解释了类似的场景,但我无法将其转移到我的问题上。具体来说,当我写这个时:

public T get() {
        Type[] actualTypeArguments = ((ParameterizedType) getClass())
                                         .getActualTypeArguments();
    }

我收到编译器错误,提示我无法转换为 ParameterizedType,但我不明白为什么。谁能解释一下如何实现这一目标?

最佳答案

这是一种方法:

public class <T> RemoteVariable {
    private final RemoteDeviceProxy wrappedDevice;
    private final Class<T> clazz;

    public RemoteVariable(RemoteDeviceProxy wrappedDevice, Class<T> clazz) {
        this.wrappedDevice = wrappedDevice;
        this.clazz = clazz;
    }

    public T get() {
        if(clazz == Boolean.class){return clazz.cast(wrappedDevice.getBoolean());}
        else if(clazz == Integer.class){return clazz.cast(wrappedDevice.getInteger());}
        // ...
    }

    // ...
}

关于java - 如何为类似 ResultSet 的 API 实现通用包装器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17317327/

相关文章:

java - 泛型构造函数在 Java 中的作用是什么?

c# - 通过递归动态地使用 XElement 构建 Xml

c# - 将 SetValue 与隐式转换结合使用

java - Spring Ehcache3 导致键类型和值类型异常

java - 服务器-客户端之间的文件上传和下载

Python:chrome.exe 的通用 webbrowser.get().open() 不起作用

.net - 以编程方式访问 .NET 类型的 CIL

java - 内部类无法访问从内部调用构造函数的方法初始化的外部类成员变量

java - 为什么我应该使用 java 和 php

具有通用类型边界的 Java Builder 模式