Java 访问在另一个类中创建的对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4401784/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 17:01:57  来源:igfitidea点击:

Accessing an object created in another class

javaobject

提问by system

I create a thread in my main class. The thread has a timer which writes and reads on a socket.

我在主类中创建了一个线程。该线程有一个在套接字上写入和读取的计时器。

I need to call a method in the thread class e.g writeSomething() from another class outside of where it was declared(Main).

我需要在线程类中调用一个方法,例如从声明它的位置(Main)之外的另一个类调用 writeSomething()。

How is the object referenced from another class?

对象是如何从另一个类引用的?

Edit

编辑

public static Thread connectionThread;

ModelJTable table = new ModelJTable();
connectionThread = new Thread(new ConnectionThread(table), "connectionThread");
connectionThread.start();

I have a method in the thread class

我在线程类中有一个方法

public void openFile(String fileName){
    String request = "open;" + fileName;
    out.print(request);
}

I want to access if from another class(the JTable class)

我想从另一个类(JTable 类)访问 if

String open = "open;" + getname + ";" + getpath;
// This doesnt work 
ConnectionThread.openFile(open);

This call gives an error

这个调用给出了一个错误

No enclosing instance of the type ConnectionThread is accessible in scope

在范围内没有可访问的 ConnectionThread 类型的封闭实例

采纳答案by Jigar Joshi

Either pass it in constructor of second class OR make it static in first class, OR serialize it

要么在第二类的构造函数中传递它,要么在第一类中将其设为静态,要么将其序列化

way 1: static one

方式一:静态方式

Class A{
public static int a=0;
}

Class B{
public void someMethod(){
A.a = 10;
}
}

回答by jzd

Pass a reference to the Thread to the class that needs to call the method.

将 Thread 的引用传递给需要调用该方法的类。