Passing a return value to an anonymous class

I am trying to pass the return value from task scheduling to an anonymous class, but I'm having problems. If I set the return value to a final variable, it says that it is not initialized:

/* Not initialized */
final BukkitTask task = Bukkit.getScheduler().runTaskTimer(plugin, new Runnable() {

    public void run() {
        /* irrelevant code */
        task.cancel();
    }

}, 0L, 20L);

I also tried passing the variable by calling the method inside the anonymous class, however it changes the return type to void, and therefore I cannot pass the correct value:

BukkitTask temp = null;
/* Returns void */
temp = Bukkit.getScheduler().runTaskTimer(plugin, new Runnable() {

    private BukkitTask task;

    public void initTask(BukkitTask task) {
        this.task = task;
    }

    public void run() {
        /* irrelevant code */
        task.cancel();
    }

}.initTask(temp), 0L, 20L);

How to pass return value to an anonymous class inside code?

+4
source share
5 answers

You can define this class

class Box<T> {
    public volatile T value;
}

and use it as follows:

final Box<BukkitTask> taskBox = new Box<BukkitTask>();
taskBox.value = Bukkit.getScheduler().runTaskTimer(plugin, new Runnable() {
    public void run() {
        /* irrelevant code */
        taskBox.value.cancel();
    }
}, 0L, 20L);

However taskBox.value, runit may still nulldepend on when runTaskTimerthe runnable actually executes.

+3

, , , . , .

+1

, , !

init, !:

BukkitTask task = null;
task = Bukkit.getScheduler().runTaskTimer(plugin, new Runnable() {

    private BukkitTask task;

    public Runnable initTask(BukkitTask task) {
        this.task = task;
        return this;
    }

    public void run() {
        /* irrelevant code */
        task.cancel();
    }
}.initTask(task), 0L, 20L);
0

.

 public static void main(String[] args) {
    final Object objectA[] = new String[1];

    new Thread(new Runnable() {
        private A refA = null;
        public void run() {
            objectA[0] = "Hello World or your object";
        }
    }).start();;

    while (objectA[0] == null){

    }
    System.out.println(objectA[0]);
}
0

All Articles