0

IntelliJ wants me to make my variables final, but I need them to change (I will be modifying them within the method). How can I fix this issue?

Here is my code, I've never had this issue before:

public void openDoor(int id, int x, int y, int face, int type) {
    Server.getTaskScheduler().schedule(new Task(0, true) {
        @Override
        protected void execute() {
            ObjectManager.deleteObject(c, x, y); //Error is here
        }
    });
}
4

2 回答 2

2

You'll have to figure a clever way around it because this is a requirement in Java. You can't modify local variables or method parameters from within an anonymous inner class that are declared outside of it. One possible solution is to create a "holder" class, like:

class Holder {
    Object c;
    int x;
    int y;
}

Then have your method accept a final Holder, and the anonymous class can modify the content of the Holder. Another (ugly) option is to make each of the affected parameters an array. Then the array can be final, but, again, you're free to modify the content.

The best option is probably to stop and ask yourself why you need to modify those variables in the first place. Probably, your task execution should be returning some value instead.

于 2013-01-01T00:56:26.133 回答
1

添加另一个答案,因为我倾向于认为更方便的解决方案是复制变量,有点像这样:

public void openDoor(int id, final int f_x, final int f_y, int face, int type) {
    Server.getTaskScheduler().schedule(new Task(0, true) {
        int x = f_x, y = f_y; /* Either here... */

        protected void execute() {
            int x = f_x, y = f_y; /* ... or here, depending on your requirements */
            ObjectManager.deleteObject(c, x, y);
        }
    });
}

这样,您不必每次都需要通过“Holder”对象间接访问数据。

当然,这两种方式都很丑陋,但这只是 Java。没办法。:)

于 2013-01-01T01:13:36.577 回答