假设我有一个应用程序:
my_Application the_application = new my_Application();
Parser parser = new Parser;
parser.log();
然后,获取一些方法 parser.log() 将字符串扔到应用程序的窗口中?
public void log(String input){
// Get the instance of the object which created this object, call it 'daddy'
daddy.log(input);
}
而在my_Application的原始类中,有一个方法log
。
public void log(String input){
textPane.append("[LOG] " + input);
}
最佳答案
就您的代码而言,您不能。您的解析器
将需要对the_application
的引用。一种方法是在构造函数中执行此操作:
public class Parser {
private my_Application daddy = null;
public Parser(my_Application app) {
daddy = app;
}
public void log(String input){
daddy.log(input);
}
}
然后您创建解析,如下所示:
my_Application the_application = new my_Application();
Parser parser = new Parser(the_application);
顺便说一下,用下划线声明 java 类并不是一种常见的做法。而是使用驼峰命名法,例如 MyApplication
关于java - 有没有办法获取创建另一个对象的对象的实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31330537/