我应该如何投放具有多个边界的Java通用? [英] How should I cast for Java generic with multiple bounds?
问题描述
是否可以将Java中的对象转换为组合的通用类型?
我有一个方法:
public static< T extends Foo& Bar> void doSomething(T object){
// do stuff
}
这个方法没有问题,如果我有一个类实现两个接口(Foo& Bar)。
问题是当我需要调用这个方法我需要的对象传递给它作为 java.lang.Object
接收,我需要强制转换以使编译器愉快。
问题出在了函数如下:
public void problemFunction(Object o){
if(o instanceof Foo& o instanceof Bar){
doSomething((Problematic cast)o);
}
}
}
不幸的是,没有法律效力,你可以做出来满足这种情况。必须有一个已知的类型来实现您需要的所有界面作为界限,以便您可以投射到它。
接口Baz扩展Foo,Bar {}
public void caller(Object w){
doSomething((Baz)w);
}
如果已知其他类型,例如 Baz
,为了满足边界,你可以测试这些类型,并在你的调用者中有一个分支,调用
doSomething
并转换这些类型。
您还可以使用委托,创建您自己的类 Baz
,它满足 doSomething
。然后将您传递的对象包装在 Baz
类的实例中,并将该包装传递给 doSomething
p>
私人静态类FooBarAdapter实现Foo,Bar {
private final Object adaptee;
FooBarAdapter(Object o){
adaptee =(Foo)(Bar)o;
}
public int flip(){return((Foo)adaptee).flip(); }
public void flop(int x){((Foo)adaptee).flop(x); }
public void blort(){((Bar)adaptee).blort(); }
}
public void problemFunction(Object o){
doSomething(new FooBarAdapter(o));
}
Is it possible to cast an object in Java to a combined generic type?
I have a method like:
public static <T extends Foo & Bar> void doSomething(T object) {
//do stuff
}
Calling this method is no problem if I have a class that implements both interfaces (Foo & Bar).
The problem is when I need to call this method the object I need to pass to it is received as java.lang.Object
and I need to cast it to make the compiler happy. But I can't figure out how to make this cast.
edit:
The problem lies in a function like this:
public void problemFunction (Object o) {
if ( o instanceof Foo && o instanceof Bar) {
doSomething((Problematic cast) o);
}
}
}
Unfortunately, there is no legal cast that you can make to satisfy this situation. There must be a single type known to implement all of the interfaces that you need as bounds, so that you can cast to it. The might be a type you create for the purpose, or some existing type.
interface Baz extends Foo, Bar { }
public void caller(Object w) {
doSomething((Baz) w);
}
If other types are known, like Baz
, to meet the bounds, you could test for those types, and have a branch in your caller that calls doSomething
with a cast to those types. It's not pretty.
You could also use delegation, creating your own class Baz
that meets the bounds required by doSomething
. Then wrap the object you are passed in an instance of your Baz
class, and pass that wrapper to doSomething
.
private static class FooBarAdapter implements Foo, Bar {
private final Object adaptee;
FooBarAdapter(Object o) {
adaptee = (Foo) (Bar) o;
}
public int flip() { return ((Foo) adaptee).flip(); }
public void flop(int x) { ((Foo) adaptee).flop(x); }
public void blort() { ((Bar) adaptee).blort(); }
}
public void problemFunction (Object o) {
doSomething(new FooBarAdapter(o));
}
这篇关于我应该如何投放具有多个边界的Java通用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!