Java可以在数组中存储方法吗?

时间:2022-06-06 16:22:42

Well I wrote some code and all I was doing was for loops, but changing which method I called. I tried using a for loop so it'd be a bit neater (and out of curiosity to see if it could be done), but it doesn't compile when I do it this way, because it doesn't recognize an item in an array as a method, I think. This is what I have:

好吧,我写了一些代码,我所做的只是循环,但改变了我调用的方法。我尝试使用for循环,所以它有点整洁(出于好奇,看看是否可以完成),但是当我这样做时它不会编译,因为它不能识别一个项目我想,数组作为一种方法。这就是我所拥有的:

String[] moveArray = {moveRight,moveDown,moveLeft,moveUp};
for (i = 0; i < 4; i++) {
    while (myWumpus.moveArray[i]) {
        myWumpus.moveArray[i];
        generator.updateDisplay();
    }
}

When I try compile I get

当我尝试编译时,我得到了

not a statement myWumpus.moveArray[i]();
';' expected myWumpus.moveArray[i]();

(It refers to the first statement in the while loop)

(它指的是while循环中的第一个语句)

So, I think it's maybe because I'm making it an Array of type String? Is there a type Method? Is this at all possible? Any solutions welcome :). Also, I can get it to work using 4 while loops, so you don't need to show me that solution. Thanks!

所以,我认为这可能是因为我正在使它成为String类型的数组?有类型方法吗?这是可能吗?任何解决方案欢迎:)。此外,我可以使用4 while循环来使其工作,因此您无需向我展示该解决方案。谢谢!

4 个解决方案

#1


14  

You cannot store methods directly in arrays. However you can store objects, which implement the same method differently. For example:

您无法直接在数组中存储方法。但是,您可以存储以不同方式实现相同方法的对象。例如:

Mover[] moveArray = {new RightMover(), new DownMover() new LeftMover(), new UpMover() };
for (i = 0; i < 4; i++) {
    while (myWumpus.moveArray[i]) {
        moveArray[i].move();
        generator.updateDisplay();
    }
}

#2


5  

You can't store methods in arrays in Java, because methods aren't first-class objects in Java. It's a reason some people prefer to use other languages like Python, Scheme, etc.

您无法在Java中的数组中存储方法,因为方法不是Java中的第一类对象。这是一些人喜欢使用Python,Scheme等其他语言的原因。

The work-around is to create an interface which contains one method, then create four classes implementing that interface - the MoveRight, MoveLeft, etc... classes. Then you can store instances of those classes in your array and call them all the same way.

解决方法是创建一个包含一个方法的接口,然后创建实现该接口的四个类 - MoveRight,MoveLeft等......类。然后,您可以在数组中存储这些类的实例,并以相同的方式调用它们。

#3


5  

Yes, you can store methods in arrays using Reflection, however it is likely that what you actually want to do in this situation is use polymorphism.

是的,您可以使用Reflection将方法存储在数组中,但是在这种情况下您实际想要做的事情可能是使用多态。

As an example of polymorphism in relation to your problem - say you created an interface as follows:

作为与您的问题相关的多态性的一个例子 - 假设您创建了一个接口,如下所示:

public interface MoveCommand {
    void move();
}

You can then create implementations as follows:

然后,您可以按如下方式创建实现:

public class MoveLeftCommand implements MoveCommand {
    public void move() {
        System.out.println("LEFT");
    }
}

etc. for the other move options. You could then store these in an MoveCommand[] or collection like a List<MoveCommand>, and then iterate over the array/collection calling move() on each element, for example:

等其他移动选项。然后,您可以将它们存储在MoveCommand []或集合中,如List ,然后遍历调用每个元素上的move()的数组/集合,例如:

public class Main {

    public static void main(String[] args) {
        List<MoveCommand> commands = new ArrayList<MoveCommand>();
        commands.add(new MoveLeftCommand());
        commands.add(new MoveRightCommand());
        commands.add(new MoveLeftCommand());

        for (MoveCommand command:commands) {
            command.move();
        }
    }

}

Polymorphism is very powerful, and the above is a very simple example of something called the Command Pattern. Enjoy the rest of your Wumpus World implementation :)

多态性非常强大,以上是一个非常简单的命令模式示例。享受您的Wumpus World实施的其余部分:)

#4


4  

You can't call methods like that. But you can using reflection:

你不能这样调用这样的方法。但你可以使用反射:

Just change the first line in the while-loop to:

只需将while循环中的第一行更改为:

Method m = myWumps.getClass().getMethod(moveArray[i]); // if the method is void
m.invoke(myWumps);

(you will have to declare/catch a few exceptions)

(你必须声明/捕获一些例外)

But you'd better avoid reflection, and use the Command pattern instead.

但是你最好避免反射,而是使用Command模式。

#1


14  

You cannot store methods directly in arrays. However you can store objects, which implement the same method differently. For example:

您无法直接在数组中存储方法。但是,您可以存储以不同方式实现相同方法的对象。例如:

Mover[] moveArray = {new RightMover(), new DownMover() new LeftMover(), new UpMover() };
for (i = 0; i < 4; i++) {
    while (myWumpus.moveArray[i]) {
        moveArray[i].move();
        generator.updateDisplay();
    }
}

#2


5  

You can't store methods in arrays in Java, because methods aren't first-class objects in Java. It's a reason some people prefer to use other languages like Python, Scheme, etc.

您无法在Java中的数组中存储方法,因为方法不是Java中的第一类对象。这是一些人喜欢使用Python,Scheme等其他语言的原因。

The work-around is to create an interface which contains one method, then create four classes implementing that interface - the MoveRight, MoveLeft, etc... classes. Then you can store instances of those classes in your array and call them all the same way.

解决方法是创建一个包含一个方法的接口,然后创建实现该接口的四个类 - MoveRight,MoveLeft等......类。然后,您可以在数组中存储这些类的实例,并以相同的方式调用它们。

#3


5  

Yes, you can store methods in arrays using Reflection, however it is likely that what you actually want to do in this situation is use polymorphism.

是的,您可以使用Reflection将方法存储在数组中,但是在这种情况下您实际想要做的事情可能是使用多态。

As an example of polymorphism in relation to your problem - say you created an interface as follows:

作为与您的问题相关的多态性的一个例子 - 假设您创建了一个接口,如下所示:

public interface MoveCommand {
    void move();
}

You can then create implementations as follows:

然后,您可以按如下方式创建实现:

public class MoveLeftCommand implements MoveCommand {
    public void move() {
        System.out.println("LEFT");
    }
}

etc. for the other move options. You could then store these in an MoveCommand[] or collection like a List<MoveCommand>, and then iterate over the array/collection calling move() on each element, for example:

等其他移动选项。然后,您可以将它们存储在MoveCommand []或集合中,如List ,然后遍历调用每个元素上的move()的数组/集合,例如:

public class Main {

    public static void main(String[] args) {
        List<MoveCommand> commands = new ArrayList<MoveCommand>();
        commands.add(new MoveLeftCommand());
        commands.add(new MoveRightCommand());
        commands.add(new MoveLeftCommand());

        for (MoveCommand command:commands) {
            command.move();
        }
    }

}

Polymorphism is very powerful, and the above is a very simple example of something called the Command Pattern. Enjoy the rest of your Wumpus World implementation :)

多态性非常强大,以上是一个非常简单的命令模式示例。享受您的Wumpus World实施的其余部分:)

#4


4  

You can't call methods like that. But you can using reflection:

你不能这样调用这样的方法。但你可以使用反射:

Just change the first line in the while-loop to:

只需将while循环中的第一行更改为:

Method m = myWumps.getClass().getMethod(moveArray[i]); // if the method is void
m.invoke(myWumps);

(you will have to declare/catch a few exceptions)

(你必须声明/捕获一些例外)

But you'd better avoid reflection, and use the Command pattern instead.

但是你最好避免反射,而是使用Command模式。