Java中的未绑定泛型返回类型

时间:2017-03-30 01:42:25

标签: java generics api-design

我正在玩有关构建Java API的一些想法,今天我花了一些时间思考这段代码:

public <T> T getField1(Class<?> type, Class<T> retvalType, String fieldName) {
  Object retval = ...; // boring reflection code - value could be dog, could be duck
  return retvalType.cast(retval); // cast to expected - exception is raised here
}

// usage - we manually repeat the LHS type as a parameter
int foo = getField(o, Integer.class, "foo");

这就是我通常编写API的方式,因为他认为指定retvalType会给我额外的类型安全性。但是吗?

因为我们涉及到反射,所以retval类型是未知的。仅当retvalType是非泛型时,第二行上的强制转换才能可靠地捕获类型不匹配。另一方面,即使我们不进行此显式转换,Java运行时也会在将其设置为变量时转换通用结果 - 换句话说,如果我们将上面的代码重写为:

public <T> T getField2(Class<?> type, String fieldName) {
  return ...; // boring reflection code - the value type will be checked when we assign it
}

// usage - exception is raised at the next line if types don't match
int foo = getField(o, "foo");

后一种代码的优点是使用更紧凑,我们不必重复自己。缺点是类型转换异常来自非显而易见的地方(在调用站点没有显式转换),但我开始认为这没关系 - 通过指定类型文字,我们只重复我们已经知道的,但最终由于反思,程序的稳健性仍然无法保证。

任何人都可以提出一个好的论据,为什么第一个片段比第二个片段更可取?

编辑1:

一个论点是,通过将期望的类型作为参数,我们可以满足在不更改API的情况下进行非平凡强制的需要。

例如,查找字段可能属于Date类型,但我们可能会请求long,可以通过date.getTime()进行内部转换。这对我来说似乎有些牵强附会,并且存在混合责任的风险。

另一方面,不传递类型会限制输入依赖性,这使得API对更改更加健壮。 (提示“信息隐藏”,“不稳定性指标”等)。

1 个答案:

答案 0 :(得分:1)

在与@shmosel的对话中,我发现当LHS类型是泛型类型时,第二个版本所依赖的运行时强制转换不一定会发生。

例如,考虑代码:

class Foo<T> {
  void a1(Object o) {
    // forces to be explicit about the chance of heap polution
    @SuppressWarning("unchecked")
    Set<String> a = (Set<String>) getField1(o, Set.class, "foo");
    T c = (T) getField1(o, Set.class, "foo"); // guaranteed not to compile
  }

  void a2(Object o) {
    // implicit chance of heap polution in case of Set<Date>
    Set<String> a = (Set<String>) getField2(o, "foo");
    T c = getField2(o, "foo"); // will succeed even if foo is Date
  }
}

换句话说,通过在getField()方法中进行转换,我们得到了一个硬保证,即该值是指定的类,即使它没有被使用,也没有被赋值给Object变量(发生了通常在动态语言和反思库中)。

相关问题