2016-10-25 29 views
1

我一直在阅读Java中的通配符,但我无法弄清楚在接口方法声明的实现中如何解决集合的通配符类型。您可以在技术上通过检查集合中的某个对象来发现该类型,但这不会允许您解决集合中的类型,并且如果该集合为空,则会失败。在接口的@Override实现中解析通配符类型

public interface SomeInterface { 
    void addAThing(Object thing); 
    void addAListOfThings(Collection< ?> things); 
} 

public class SomeInterfaceImplementation implements SomeInterface { 
    @Override 
    public void addAThing(Object thing) { 
     if (thing instanceof Foo) { 
      /* thing has been discovered to be of type Foo 
      so now it can be assigned to an explicit Foo object */ 
      Foo fooThing = (Foo) thing; 
     } 
    } 

    @Override 
    public void addAListOfThings(Collection< ?> things) { 
     //this fails if things is empty 
     if (things.toArray()[0] instanceof Foo) { 
      /* things type has been discovered(maybe) to be of type Foo 
      but now we are unable cast without an unchecked cast exception */ 
      Collection<Foo> fooThings = (Collection<Foo>) things; 
     } 
    } 
} 

有没有一种合适的方法我不知道这样做?

+0

没有,因为类型擦除,有没有办法恢复运行时的原始类型。即使你的建议不起作用,因为'List '很可能有'String'作为它的第一个元素,而'Integer'作为其第二个。 –

+0

@TavianBarnes好点,我在那里做了一个糟糕的假设。 – nukeforum

回答

3

如果您希望您的方法使用泛型,它应该在签名或类/接口定义中定义。

public interface SomeInterface<T> { 
    void addAThing(T thing); 
    void addAListOfThings(Collection<T> things); 
} 

和执行类泛型类型Foo的,:

public class SomeInterfaceImplementation implements SomeInterface<Foo> { 

    @Override 
    public void addAThing(Foo thing) { 
     // thing is of type Foo 
    } 

    @Override 
    public void addAListOfThings(Collection<Foo> things) { 
     // things is a collection of Foo 
    } 
} 
+0

我感觉有点傻。我以前看过这个,但由于某种原因,我没有认识到我可以在这个特殊情况下使用它。 – nukeforum

+0

不错。用60秒的时间仔细调整我。 –