Моя проблема проста: мне нужно получить доступ к переменной history
(которая объявлена в классе BinaryServer) из другого класса. Я использую больше классов для запуска этого кода. Это просто простой клиент и сервер сокетов. Клиент отправляет на сервер двоичный код/текст, а сервер переводит его в текстовый/двоичный код и отправляет его обратно клиенту. Я могу предоставить все классы, если это необходимо.Доступ к статической переменной из другого класса
BinaryServer класс
import java.net.*;
import java.util.ArrayList;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import graphics.gui;
public class BinaryServer extends gui implements ActionListener,Runnable
{
private ServerSocket server;
private Socket client;
public String text;
private BufferedReader reader;
public static ArrayList<String> history;
public static String binary_letter;
public static String[] letter;
public static int i;
public static String[] binary;
public static String sendback;
public static void main(String[] args)throws IOException
{
BinaryServer instance=new BinaryServer();
gui.buildframe(310,360,"Binary translator server");
gui.buildpane(300,300,true);
gui.buildbutton(300,20,"Translate");
instance.server(63400);
}
public void server(int port)throws IOException
{
history=new ArrayList<String>(100);
server=new ServerSocket(port);
button.addActionListener(this);
while(true)
{
client=server.accept();
reader=new BufferedReader(new InputStreamReader(client.getInputStream()));
text=reader.readLine();
history.add(text);
message.setText(message.getText()+"\n"+text+": ");
}
}
@Override
public void actionPerformed(ActionEvent e)
{
Thread response=new Thread(new BinaryServer());
if(text.contains("0"))
{
int length=text.length();
letter=new String[length+1];
sendback="";
int begin=-8;
int end=0;
for(i=1;i<=length/8;i++)
{
begin=begin+8;
end=i*8;
binary_letter=text.substring(begin,end);
Libary.translate();
message.setText(message.getText()+letter[i]);
sendback=sendback+letter[0+i];
}
}
else
{
int length=text.length();
letter=new String[length+1];
binary=new String[length+1];
sendback="";
for(i=1;i<=length;i++)
{
letter[i]=text.substring(i-1,i);
Libary.encode();
message.setText(message.getText()+binary[i]);
sendback=sendback+binary[0+i];
}
}
response.start();
}
public void run()
{
try
{
Socket feedback=new Socket("localhost",63403);
PrintWriter writer=new PrintWriter(feedback.getOutputStream(),true);
writer.println(sendback);
feedback.close();
return;
}
catch(IOException exc)
{
System.out.println("");
}
}
}
BinaryHistory класс (Тот, который я хочу доступа переменную из)
public class BinaryHistory { public static void main(String[] args) { show(); } public static void show() { System.out.println(BinaryServer.history); }
Когда я получить доступ к переменной history
из класса BinaryHistory, это все дни ноль.
вы называете сервер в любом месте перед доступом? серверный метод, похоже, инициализирует его –
. Здесь я вижу 2 сети, и нет никакого инициализации класса сервера. – Dima
Я работаю в eclipse, и он находится в одном окружении. Даже после расширения класса BinaryServer переменная по-прежнему равна нулю. –