[英]Cast an object that is not known until runtime to its type
我有一棵包含三类节点的树。 例如,根节点具有另一个节点类的左节点和右节点。 所有这三个类都实现一个接口。 问题是在运行时之前,我不知道左节点和右节点具有哪种类型,但是我需要强制转换为特定类型,否则无法访问节点的变量。
那么如何在运行时将这些节点转换为它的类型?
//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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.