Scheduler help {solved]

Discussion in 'Plugin Development' started by kabbage, Feb 12, 2012.

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

    kabbage

    I'm trying to get a value from an event into a delayed scheduler. However when I try to do this, it says I "Cannot refer to a non-final variable player inside an inner class defined in a different method"

    I can't set the variable to final though, but I still need it referenced in the task every time it gets called.

    Code:
     
    Map<Player, Boolean> Immune = new HashMap<Player, Boolean>();   
         
    public void onEntityDamage (EntityDamageEvent event) {
    Player player = (Player) event.getEntity()
     
    plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
     
                    public void run() {
                        Immune.put(player, false);
                           
                    }
                }, 20L);
    }
    How would I reference "player" in the task?
     
  2. First of all: Map<Something, Boolean> is a wrong collection design! You only need 2 states: yes or no. And you can use a HashSet for that: if a player is in there, it is true, otherwise false.
    So you should use a HashSet<String>, with the values being the active player names.

    Regarding your actual problem: You could either pass the player('s name) to your class that implements Runnable, or just make the local variable final, as you IDE suggested. I can't see a reason why you wouldn't be able to.

    You could just do:
    Code:
    final String playerName = player.getName();
    And then use that String in your run() method.
     
    kabbage likes this.
  3. Offline

    kabbage

    Oh, yeah. I was thinking it would create a variable that could never be changed, but it's re-created every time the event is called...(I think)

    Thanks.
     
Thread Status:
Not open for further replies.

Share This Page