[英]A method that returns an Collection is returning an array when it's invoked by reflection?
There is a method in the Bukkit API: getOnlinePlayers()
: Bukkit API中有一个方法: getOnlinePlayers()
:
public static Collection<? extends Player> getOnlinePlayers()
{
return server.getOnlinePlayers();
}
In older versions of Bukkit it returns an array of Player[]
; 在旧版本的Bukkit中,它返回Player[]
的数组; while in newer versions it returns a Collection<Player>
. 而在较新的版本中,它返回Collection<Player>
。
I wanted to make it possible to have compatibility in both new and old versions, so I use reflection to invoke it: 我想使其在新旧版本中都具有兼容性,所以我使用反射来调用它:
public static Collection<Player> getOnlinePlayers(){
Method m;
Object obj = null;
try
{
m = Bukkit.class.getMethod("getOnlinePlayers");
obj = m.invoke(null, (Object[])null);
}catch (...){ // omitted
throw new RuntimeException(...); // omitted
}
if (obj instanceof Player[]){
System.out.println("array"); // Used for testing
return Arrays.asList((Player[])obj);
}else if (obj instanceof Collection){
System.out.println("collection"); // Used for testing
return (Collection<Player>)obj;
}else{
throw new RuntimeException(...); // omitted
}
}
Then here's the problem: When I tried this code in both new and old versions of Bukkit, it always prints "array". 然后是问题所在:当我在Bukkit的新旧版本中都尝试此代码时,它始终会打印“ array”。 I am wondering why this would happen? 我想知道为什么会这样?
I've found out why. 我发现了原因。 The reason is that I'm testing against Spigot, which is an API based on Bukkit, but has kept the method getOnlinePlayers() returning an array even after Bukkit has changed that. 原因是我正在针对Spigot(基于Bukkit的API)进行测试,但即使Bukkit进行了更改,但仍使getOnlinePlayers()方法返回数组。 When I test against Bukkit, it prints out "collection". 当我对Bukkit进行测试时,它会打印出“集合”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.