gpt4 book ai didi

java - 将直到运行时才知道的对象转换为其类型

转载 作者:太空宇宙 更新时间:2023-11-04 09:52:00 25 4
gpt4 key购买 nike

我有一个包含三类节点的树。例如,根节点具有另一个节点类的左节点和右节点。所有三个类都实现一个接口(interface)。问题是在运行时我不知道左右节点有哪种类型,但我需要转换为特定类型,否则我无法访问节点的变量。

那么如何在运行时将这些节点转换为其类型?

//node has a attribut left of type of interface Visitable
public Visitable left;

....

//Visitable is the Interface that the three classes has implemented
(CLASS) leftNode = (CAST_TO_ITS_TYPE) node.left;

//I only can access isVisited, if leftNode is casted to its class
Boolean visited = leftNode.isVisited;

我尝试了“instanceof”,但这不起作用,因为 leftNode 可能尚未初始化。

Visitable leftNode;
if (node.left instanceof NodeClassOne) {
leftNode = (NodeClassOne) node.left;
} else if (node.left instanceof NodeClassTwo) {
leftNode = (NodeClassTwo) node.left;
}

Boolean visited = leftNode.isVisited;

最佳答案

事实上你做得对。 node.left 应为not null 才能正确定义其类型。

Visitable leftNode = null;

if (node.left != null) {
if (node.left instanceof NodeClassOne)
leftNode = (NodeClassOne) node.left;
else if (node.left instanceof NodeClassTwo)
leftNode = (NodeClassTwo) node.left;
}

Boolean visited = leftNode != null ? leftNode.isVisited : Boolean.FALSE;

关于java - 将直到运行时才知道的对象转换为其类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54616975/

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