gpt4 book ai didi

java - 在java中通过实例名称作为字符串调用实例方法

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

类树中我收到错误消息:

The method removeparent() is undefined for the type String.

我想将字符串“Grandchild3”转换为MyTreeNode类实例的对象,然后我可以使用removep("Grandchild3")调用像这样的方法Grandchild3.removeparent()
我怎样才能做到这一点?

这是 MyTreeNode 类:

public class MyTreeNode<T>{
private T data = null;
private List<MyTreeNode> children = new ArrayList<>();
private MyTreeNode parent = null;

public MyTreeNode(T data) {
this.data = data;
}

public void addChild(MyTreeNode child) {
child.setParent(this);
this.children.add(child);
}

public void addChild(T data) {
MyTreeNode<T> newChild = new MyTreeNode<>(data);
newChild.setParent(this);
children.add(newChild);
}

public void addChildren(List<MyTreeNode> children) {
for(MyTreeNode t : children) {
t.setParent(this);
}
this.children.addAll(children);
}

public List<MyTreeNode> getChildren() {
return children;
}

public T getData() {
return data;
}

public void setData(T data) {
this.data = data;
}

private void setParent(MyTreeNode parent) {
this.parent = parent;
}

public MyTreeNode getParent() {
return parent;
}

public void removeparent() {
this.parent = null;
}
public void removeChild(MyTreeNode<T> child)
{
this.children.remove(child);
}

}

这是树类:

    public class Tree {

public static void main(String[] args) throws ClassNotFoundException {
// TODO Auto-generated method stub
MyTreeNode<String> root = new MyTreeNode<>("Root");

MyTreeNode<String> child1 = new MyTreeNode<>("Child1");
child1.addChild("Grandchild1");
child1.addChild("Grandchild2");

MyTreeNode<String> child2 = new MyTreeNode<>("Child2");
child2.addChild("Grandchild3");

root.addChild(child1);
root.addChild(child2);
root.addChild("Child3");

root.addChildren(Arrays.asList(
new MyTreeNode<>("Child4"),
new MyTreeNode<>("Child5"),
new MyTreeNode<>("Child6")
));

for(MyTreeNode<String> node : root.getChildren()) {
System.out.println(node.getData());
}

printTree(root, " ");

removep("Grandchild3"); //error message"The method removeparent() is undefined for the type String"

printTree(root, " ");

}

private static void printTree(MyTreeNode<String> node, String appender) {
System.out.println(appender+node.getData());
for (MyTreeNode each : node.getChildren()){
printTree(each, appender + appender);
}
}

public static void removep(MyTreeNode<String> node)
{
node.getParent().removeChild(node);
node.removeparent();

}

}

最佳答案

所以基本上你想要的是将字符串转换为类对象。现在可能有几种方法可以完成,但在此处使用的上下文中,似乎您可以简单地传递适当的对象,而不是弄乱字符串。

因此,在您的情况下,最合适的方法是创建一个方法,该方法接收字符串名称和树的顶部节点,并迭代树以查找具有给定名称的节点。找到后,该方法返回节点。

然后您可以使用该方法从名称中获取节点,然后调用removep

关于java - 在java中通过实例名称作为字符串调用实例方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46386899/

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