Java 执行通用接口方法的正确方法?

Java 执行通用接口方法的正确方法?,java,generics,Java,Generics,我想做一个我可以做的界面 public interface Getter { T get(String location); } public class IntegerGetter { Integer get(String location) { Object x = foo(location); if (!(x instanceOf Integer)) { throw Exception } return (Integer) x; } } 如何正确地安

我想做一个我可以做的界面

public interface Getter {
  T get(String location);
}

public class IntegerGetter {
  Integer get(String location) {
    Object x = foo(location);
    if (!(x instanceOf Integer)) { throw Exception }
    return (Integer) x;
  }
}

如何正确地安排泛型来实现这一点?一个选项似乎是使T成为接口本身的类型参数,例如,
Getter
IntegerGetter
,但由于该参数仅用于一个方法,因此将其作为方法参数更有意义。但是,有人告诉我,仅仅将type参数作为方法的返回类型是危险的,例如,
T get

您基本上实现了一个类似于的接口。你可以把它作为参考。接口需要使用参数
T
键入,否则
get
方法可以在调用上下文中使用,它可以返回任何类型的对象

我被告知,将type参数作为方法的返回类型是危险的,例如
T get

这并不比你已经拥有的更危险

稍微简化您的
积分机

class IntegerGetter {
  Integer get(String location) {
    return (Integer) foo(location);
  }
}
您可以为
String
s定义等效类:

class StringGetter {
  String get(String location) {
    return (String) foo(location);
  }
}
假设
foo(String)
在这两个类中是同一个方法,它返回纯粹基于
位置的结果,并且不返回
null
,则至少以下一行将失败:

Integer i = new IntegerGetter().get("hello");
String s = new StringGetter().get("hello");
因为
foo(“hello”)
不能同时是
字符串和
整数

因此,您最好只使用一个实现:

class SimplerGetter {
  <T> T get(String location) {
    return (T) foo(location);
  }
}

这里的
foo
是什么?“但是,由于参数仅用于一个方法,因此将其作为方法参数更有意义。”不,没有意义。使用
Getter
IntegerGetter implements Getter
@bradimus我提供的示例非常简单,但实际上我正在构建一些与类型无关的其他方法。在这种情况下,95%的类用户不会使用该方法,但他们仍然必须提供泛型类型参数。应该说得更清楚。你还说它没有什么意义吗?如果你没有在调用时指定类型,那就有区别了,例如,
Object o=new simplegetter().get(“hello”)
Integer i = new SimplerGetter().get("hello");
String s = new SimplerGetter().get("hello");