开发者

Why I cannot call setSomething()?

开发者 https://www.devze.com 2022-12-24 01:52 出处:网络
I dont know how to acces my method of my class ProjectNode, that is returned from ExplorerManager mgr like this:

I dont know how to acces my method of my class ProjectNode, that is returned from ExplorerManager mgr like this:

mgr.getRootContext().setSomething()

getRootContext() returns Node object, but I put class ProjectNode (extends AbstractNode, abstractNode extends Node)into rootContext.

The compiler does not want to eat that line of code. But it m开发者_StackOverflow中文版ust!


If getRootContext() returns a Node, then you can only call the methods defined in Node, not in its subclasses. You can cast the return value to another class if you need that:

Node rootContext = mgr.getRootContext();
if(rootContext instanceof ProjectNode){
    ProjectNode rootProjectNode = (ProjectNode)rootContext;
    rootProjectNode.setSomething();
} else {
    //handle this case
}


((ProjectNode)mgr.getRootContext()).setSomething();

don't forget to check type!


IfsetSomething() is not a public method on Node class, you can not "feed the compiler" that code - no matter how you try. As all the wise men has spoken above, you must cast the result to the subclass that defines your setSomething() method.

0

精彩评论

暂无评论...
验证码 换一张
取 消