我有一个接口(interface),它定义了一个执行一些计算的方法
public interface Computable {
public Result compute(Foo foo);
}
我还想将一组参数传递给可以剥离的计算。我可以解决这个问题,但我想知道是否有一个带有 generics
和 var args
的优雅解决方案。类似...
public class Parameter<K,V> {
private final K key;
private final V value;
public Parameter(K key, V value) {
this.key = key;
this.value = value;
}
public K getKey() {
return this.key;
}
public V getValue() {
return value;
}
}
但是随后我不知道如何从参数列表中遍历每个参数,我将能够简单地获取键值对及其推断的类型。有人能帮我吗?这不是已经内置到 JDK 中了吗?
编辑示例:
在具体的实现中,我们会有......
public Result compute(Foo foo,
Parameter ...parameters) {
// Here I'd like to get each parameter, and have it know it's key type and value type
for(Parameter p : parameters) {
p.getKey();
p.getValue()
//implementers know what to do with their parameters
}
}
最佳答案
如AmitD mentioned in the comments ,你应该做 Computable
参数化类型:
public interface Computable<K, V> {
public Result compute(Foo foo, Parameter<K, V>... parameters);
}
然后,实现将解析 K
和V
并且类型是已知的:
public class BarBazComputable implements Computable<Bar, Baz> {
@Override
public Result compute(Foo foo, Parameter<Bar, Baz>... parameters) {
...
}
}
编辑:是的,正如 AmitD 再次提到的,您不需要解析其中一个或所有类型参数:
public class WithStringComputable<K> implements Computable<K, String> {
@Override
public Result compute(Foo foo, Parameter<K, String>... parameters) {
...
}
}
public class OhJustACoupleObjectsComputable<K, V> implements Computable<K, V> {
@Override
public Result compute(Foo foo, Parameter<K, V>... parameters) {
...
}
}
public class NumbersComputable<N1 extends Number, N2 extends Number> implements Computable<N1, N2> {
@Override
public Result compute(Foo foo, Parameter<N1, N2>... parameters) {
...
}
}
请注意,可变参数不能很好地与泛型配合使用,并且在调用compute
时,您将在调用站点收到类型安全警告。 。相反,请考虑让该方法采用 Iterable<Parameter<K, V>>
.
关于java - 使用泛型创建参数类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13283067/