gpt4 book ai didi

java - 将返回值传递给匿名类

转载 作者:搜寻专家 更新时间:2023-11-01 02:47:05 24 4
gpt4 key购买 nike

我试图将调度任务的返回值传递给匿名类,但我遇到了麻烦。如果我将返回值设置为最终变量,它会说它没有初始化:

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

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

}, 0L, 20L);

我还尝试通过调用匿名类中的方法来传递变量,但是它将返回类型更改为 void,因此我无法传递正确的值:

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);

如何在代码中将返回值传递给匿名类?

最佳答案

你可以定义这个类

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

并像这样使用它:

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);

但是,run 中的 taskBox.value 仍可能为 null,具体取决于 runTaskTimer 实际执行可运行对象的时间.

关于java - 将返回值传递给匿名类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19728434/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com