简体   繁体   English

how can you pass an object to a function as a parameter, then have the function to assign a new object of a subtype to its parameter?

[英]how can you pass an object to a function as a parameter, then have the function to assign a new object of a subtype to its parameter?

I'm trying to build up a compiler using the recursive descent parsing method and visitor pattern for semantic checking with Java.我正在尝试使用递归下降解析方法和访问者模式构建一个编译器,用于使用 Java 进行语义检查。 The thing that confuses me is to use visitor patterns, we have to create different subtypes.让我困惑的是使用访问者模式,我们必须创建不同的子类型。 However, Java doesn't pass by reference.但是,Java 没有通过引用传递。 Which caused me that I cannot end up with the right subtype for each semantic records.这导致我无法为每个语义记录找到正确的子类型。 Here is what I'm trying to implement这是我要实现的

Node node = new ExprNode();
changeNodeType(node);

public void changeNodeType(Node node) {
     node = new AddOpNode();
}

then eventually my Node type will end up with AddOpNode().那么最终我的 Node 类型将以 AddOpNode() 结束。 Is there any way that I could eventually implement this in Java?有什么方法可以最终在 Java 中实现吗?

You could just return the new node type and assign it outside of the function.您可以只返回新节点类型并将其分配到 function 之外。

Node node = new ExprNode();
node = changeNodeType();

public Node changeNodeType() {
     return new AddOpNode();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM