Java 解析接口的@Override实现中的通配符类型

Java 解析接口的@Override实现中的通配符类型,java,Java,我一直在阅读Java中的通配符,但我不知道如何在接口方法声明的实现中解析集合的通配符类型。从技术上讲,您可以通过检查集合中的一个对象来发现类型,但这不允许您解析集合中的类型,如果集合为空,则解析失败 public interface SomeInterface { void addAThing(Object thing); void addAListOfThings(Collection< ?> things); } public class SomeInterfa

我一直在阅读Java中的通配符,但我不知道如何在接口方法声明的实现中解析集合的通配符类型。从技术上讲,您可以通过检查集合中的一个对象来发现类型,但这不允许您解析集合中的类型,如果集合为空,则解析失败

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;
        }
    }
}
公共接口SomeInterface{
无效添加(对象事物);
物品(收集<?>物品)无效;
}
公共类SomeInterfaceImplementation实现SomeInterface{
@凌驾
公共无效添加(对象对象){
if(事物实例Foo){
/*这东西被发现是Foo型的
所以现在它可以被分配给一个显式的Foo对象*/
Foo fooThing=(Foo)thing;
}
}
@凌驾
公共物品(集合<?>物品){
//如果内容为空,则此操作失败
if(things.toArray()[0]Foo实例){
/*已发现(可能)事物类型为Foo类型
但是现在,如果没有未检查的强制转换异常,我们将无法强制转换*/
收集足迹=(收集)事物;
}
}
}

是否有一个我不知道的合适的方法来执行此操作?

如果您希望您的方法与泛型一起工作,那么应该在签名或类/接口定义中定义它

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

我觉得有点傻。我以前见过这种情况,但出于某种原因,我不知道我可以在这种特殊情况下使用它。很好。以60秒的准确重复超过了我。不,由于类型擦除,无法在运行时恢复原始类型。即使你的建议也行不通,因为
列表
的第一个元素很可能是
字符串
,第二个元素是
整数。@TavianBarnes说得好,我在这里做了一个错误的假设。
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
    }
}