简体   繁体   English

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

[英]Accessing an object created in another class

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 eg writeSomething() from another class outside of where it was declared(Main). 我需要在线程类中调用一个方法,例如来自声明它之外的另一个类的writeSomething()(Main)。

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类)访问

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类型的封闭实例

Either pass it in constructor of second class OR make it static in first class, OR serialize it 要么在第二个类的构造函数中传递它,要么在第一个类中使它静态,或者序列化它

way 1: static one 方式1:静态的

Class A{
public static int a=0;
}

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

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

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

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