我对Java泛型有一个奇怪的问题.实际上它可能根本不是一个问题,我可能只是因为我试图在设计中错误地使用泛型.我不会透露申请的全部细节(这是无关紧要和无聊的).
我创建了一个小片段,捕捉问题的本质.
有一个Producer界面,看起来像这样.
public interface Producer<P> {
public P produce();
}
Run Code Online (Sandbox Code Playgroud)
这个接口的实现看起来像这样
public class IntegerProducer<P> implements Producer<P> {
@Override
public P produce() {
return (P)new Integer(10);
}
}
Run Code Online (Sandbox Code Playgroud)
我在制作方法中真正需要做的就是这样
if (P instanceOf Integer) return (P)new Integer(10);
else throw new Exception("Something weird happened in the client app");
Run Code Online (Sandbox Code Playgroud)
当然,P instanceOf Integer不起作用.但如果你已经了解了我想要做的事情,请你分享一个解决方案.
谢谢你的帮助.
澄清1:问题不在于我只想返回整数.问题是在函数produce()中,我需要检查客户端程序使用的泛型类型,并根据它更改函数的行为.这不是我想要限制用于特定类型的Object(我可以使用通配符)的泛型的类型,但我需要函数produce()根据泛型中使用的Object的类型稍微不同地表现客户端代码.
ass*_*ias 10
怎么样:
public class IntegerProducer implements Producer<Integer> {
@Override
public Integer produce() {
return 10;
}
}
Run Code Online (Sandbox Code Playgroud)
由于您只IntegerProducer处理Integers,因此您不需要它是通用的.然后你可以写:
Producer<Integer> p = new IntegerProducer();
Integer i = p.produce();
Run Code Online (Sandbox Code Playgroud)
编辑
在您的评论之后,我认为唯一的方法是传递一个类参数:
public class Producer<T> {
public static void main(String[] args) throws InterruptedException {
Producer<Integer> t1 = new Producer<> ();
Producer<String> t2 = new Producer<> ();
System.out.println(t1.get(Integer.class)); //prints 10
System.out.println(t1.get(String.class)); //does not compile
System.out.println(t2.get(String.class)); //throws exception
}
public T get(Class<T> c) {
if (c == Integer.class) {
return (T) (Object) 10;
}
throw new UnsupportedOperationException();
}
}
Run Code Online (Sandbox Code Playgroud)
或者,您可以在构造函数中传递它(例如,EnumSets和EnumMaps使用的策略):
public class Producer<T> {
public static void main(String[] args) throws InterruptedException {
Producer<Integer> t1 = new Producer<> (Integer.class);
Producer<Integer> t1 = new Producer<> (String.class); //does not compile
Producer<String> t2 = new Producer<> (String.class);
System.out.println(t1.get()); //prints 10
System.out.println(t2.get()); //throws exception
}
private final Class<T> c;
public Producer(Class<T> c) {
this.c = c;
}
public T get() {
if (c == Integer.class) {
return (T) (Object) 10;
}
throw new UnsupportedOperationException();
}
}
Run Code Online (Sandbox Code Playgroud)
这显然使代码混乱,我个人会重新考虑设计以避免这种情况.
| 归档时间: |
|
| 查看次数: |
50 次 |
| 最近记录: |