Solved Calling methods from a instance of the Player.class using reflection

Discussion in 'Plugin Development' started by Shadow_tingBRO, Jul 26, 2019.

Thread Status:
Not open for further replies.
  1. So I'm using java reflection to execute methods (its complicated why) and I would like to know how to do this with the Player.class and a instance of it as its a interface and I get a NoSuchMethodException when I try to use the code below:

    Code:
    // m = "getHealth" , mc = Player.class and instance is a player in the server, which is 100% not null.
    public Object executeMethod(String m, Class mc, Object instance) {
            try {
                Method toinvoke = mc.getDeclaredMethod(m);
                return toinvoke.invoke(instance);
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            } 
        }
    
    I know this is as Player.class is a interface. Would anyone know how to declare this? I probably need to change the mc.getDeclaredMethod(m) to something else? (Im new to interfaces, only a basic understanding)
     
  2. Online

    timtower Administrator Administrator Moderator

    @Shadow_tingBRO You need to get the CraftPlayer I believe.
    But why such a complicated method for getHealth() ?
     
  3. Ohhhh that makes sense Ill try that, and Im using getHealth() for now as its very simple for testing and after ive done this I can invoke methods using reflection by passing in arguments aswell.
     
  4. Online

    timtower Administrator Administrator Moderator

    And even then, think that you need to get the right class first, which in this case might be LivingEntity, not Player.
    Do keep it mind that you can also loop over the methods to see which ones exist for that class.
     
  5. Yes thats very helpful Ill do that too.

    @timtower thanks a lot I used CraftPlayer.class instead and casted CraftPlayer over the player and now im getting the health of the player, thanks a lot.

    EDIT by Moderator: merged posts, please use the edit button instead of double posting.
     
  6. Online

    timtower Administrator Administrator Moderator

    Are you casting due to you included NMS?
     
Thread Status:
Not open for further replies.

Share This Page