具有泛型的类的方法返回List< Object>.而不是List< PluginSnapshot>使用原始类型时 [英] Method of class with generics returns List<Object> rather than List<PluginSnapshot> when using raw type

查看:53
本文介绍了具有泛型的类的方法返回List< Object>.而不是List< PluginSnapshot>使用原始类型时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是我所拥有的准系统示例.这就是编译器告诉我的:

So a barebones example of what I have you can see below. This is what the compiler is telling me:

error: incompatible types
        for (PluginSnapshot snapshot : this.platform.getPlugins()) {
                                                               ^
  required: PluginSnapshot
  found:    Object

此错误没有意义,因为类型指定为PluginSnapshot.任何想法为什么会发生这种情况?可以使用以下代码重新创建该问题.

This error makes no sense because the type is specified as PluginSnapshot. Any ideas why this could be happening? The issue can be recreated with the following code.

public class Main {
    public static void main(String... args) {
        Platform platform = null;
        for (PluginSnapshot plugin : platform.getPlugins()) {
            // ...
        }
    }
}

public interface Platform<P extends Player> {
    List<P> getPlayers();
    List<PluginSnapshot> getPlugins();
}

public interface Player {
    UUID getUniqueId();
}

public interface PluginSnapshot {
    String name();
}

推荐答案

Platform是原始类型.泛型类型Platform<P>的引用应参数化.

Platform is a raw type. References to generic type Platform<P> should be parameterized.

下面的代码应该起作用:

The following code should work:

Platform<Player> platform = ...;

for (PluginSnapshot plugin : platform.getPlugins()) {
  // ...
}

这篇关于具有泛型的类的方法返回List&lt; Object&gt;.而不是List&lt; PluginSnapshot&gt;使用原始类型时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆