Java 实例

Java instanceof

我有一个节点(Gridpane 节点),我想从 class 获取 instanceof,但是节点或任何对象我无法获取我的 class 的 instanceof,我需要添加一些东西class 去做 "instanceof" 还是我做错了?

public void Move(GridPane gridPane) {
    for (Node node : gridPane.getChildren()) {
        if (GridPane.getColumnIndex(node) == this.x && GridPane.getRowIndex(node) == this.y - 2) {
            if (node instanceof blackPawn) {
                gridPane.setRowIndex(node, this.y);
                gridPane.setColumnIndex(node, this.x);
            }
            break;
        }
    }
}

不可转换的类型;无法将 'javafx.scene.Node' 投射到 'sample.Figures.blackPawn'

blackPawn class

package sample.Figures;

import javafx.event.EventHandler;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;

public class blackPawn {
public int x;
public int y;
public ImageView IMG = createChestImage();
private int j = 0;

public blackPawn(){}

public blackPawn(int x,int y)
{
    this.x = x;
    this.y = y;
}

private ImageView createChestImage() {
    final ImageView iv = new ImageView(new Image("sample/Sprites/blackPawn.png"));

    iv.setOnMouseEntered(new EventHandler<MouseEvent>() {
        @Override
        public void handle(MouseEvent event) {
            iv.setImage(new Image("sample/Sprites/blackPawnStroke.png"));
            j = 0;
        }
    });

    iv.setOnMouseExited(new EventHandler<MouseEvent>() {
        @Override
        public void handle(MouseEvent event) {
            if(j == 0)
            iv.setImage(new Image("sample/Sprites/blackPawn.png"));
        }
    });

    iv.setOnMouseClicked(new EventHandler<MouseEvent>() {
        @Override
        public void handle(MouseEvent event) {
            iv.setImage(new Image("sample/Sprites/blackPawnStroke.png"));
            j = 1;
        }
    });

    return iv;
}

}

您正在尝试一个永远不可能的转换,编译器不允许您这样做。

例如,

String s = "hello";
Integer i = (Integer) s;

是不允许的,因为 StringInteger 不在同一个 class 层次结构中,因此永远不可能进行此转换。编译器会让你这样做:

String s = "hello";
Object o = s;
Integer i = (Integer) o;

但这会在运行时抛出 ClassCastException

在你的情况下,你可能需要以某种方式从 Node 中提取 Figure 以确定该节点是否有黑色棋子,如

if (getFigureForNode(node) instanceof BlackPawn) {
     ...

有方法

Figure getFigureForNode(Node n)

假设 BlackPawn extends(或 implementsFigure

代码味道

请注意,使用 instanceof 通常不是好的设计。您可能想使用方法 isBlackPawn(Figure f) 来代替 return f.getFigureType() == FigureType.PAWN && f.getPlayerColor() == PlayerColor.WHITE.

java instanceof运算符用于测试对象是否为指定类型的实例(class或subclass )

http://www.java2s.com/Tutorial/Java/0060__Operators/TheinstanceofKeyword.htm