Should I use this code?

Discussion in 'Plugin Help/Development/Requests' started by xXSniperzzXx_SD, Dec 1, 2014.

Thread Status:
Not open for further replies.
  1. Offline

    xXSniperzzXx_SD

    Well updating my plugin from 1.7.9 to 1.8 i noticed that getOnlinePlayers() returns a collection, and so I wanted my plugin to work with new and old versions of bukkit, so I wrote this method to get the online players, but i'm not sure if there is a better/easier way.
    Code:java
    1. public static Player[] getOnlinePlayers() {
    2. // Try the 1.7.10+ Method of getting players
    3. try
    4. {
    5. Collection<? extends Player> p = Bukkit.getOnlinePlayers();
    6. return p.toArray(new Player[p.size()]);
    7. }
    8. {
    9. // Try older way using reflection(This way it works for all versions)
    10. Class<?> c = Bukkit.class;
    11. Method method;
    12. try
    13. {
    14. method = c.getDeclaredMethod("getOnlinePlayers");
    15. Player[] players = (Player[]) method.invoke(null);
    16. return players;
    17. }
    18. {
    19.  
    20. return null;
    21. }
    22. }
    23. }

    This is the first time I've even attempted to use reflections to do something, so i don't even know if i did it right...
    But the code does in fact work for both 1.7.9 and 1.8 spigots/bukkits
     
  2. Offline

    AdamQpzm

    xXSniperzzXx_SD No, you shouldn't. You should build against the oldest version of Bukkit you intend to support.
     
  3. Offline

    xXSniperzzXx_SD

    AdamQpzm
    But then the 1.8 builds won't work with it because the same function is returning a different type.
     
  4. Offline

    AdamQpzm

    xXSniperzzXx_SD There is no 1.8 build. But the point still stands - build against the oldest version you intend to support. If the plugin was compiled against a version of the API that was expecting a Player[] return type, then a Player[] return type is available :)
     
  5. Offline

    [b]Blake[/b]

    It still can return player[], or collection.
     
  6. Offline

    xXSniperzzXx_SD

    AdamQpzm There is infact a 1.8 version if you were to visit SpigotMc, and any bukkit/spigot version newer and including 1.7.10 has getOnlinePlayers() returning a Collection<? extends Player>
     
  7. Offline

    mrCookieSlime Retired Staff

    Moved to Alternatives Section.
     
    AdamQpzm likes this.
Thread Status:
Not open for further replies.

Share This Page