我有一个第三方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/