【问题标题】:How to access static variable from another class?如何从另一个类访问静态变量?
【发布时间】:2015-04-12 02:23:07
【问题描述】:

我正在尝试从服务器类访问客户端类中的变量“名称”。这是我试图做的,但是当我打印它时,它说它是空的(?)。我怎样才能解决这个问题?提前谢谢...

客户端类

class Client {
    static Socket socket;
    static String name;

    public static void main(String[] args) throws Exception {

        String hostname = "";
        int port = 0;

        if (args.length == 3) {
            hostname = args[0];
            port = Integer.parseInt(args[1]);
            name = args[2];
            System.out.println("(" + hostname + ":" + port + ")");
        } else {
            hostname = "localhost";
            port = 3000;
            name = "default";
            System.out.println("Using all default arguments. (" + hostname + ":" + port + ")");
        }

        Client c = new Client(hostname, port);
        c.connect();
    }
}

服务器类

class Server {
    ServerSocket main;
    Helper helper;

    static class MailServer extends Thread {
        DataInputStream dataIn;
        DataOutputStream dataOut;
        int index;
        Helper helper;
        String name = Client.name; //<--- HERE
    }
}

【问题讨论】:

  • 大概客户端和服务器在不同的 JVM 中运行......或者我在这里遗漏了一些东西。

标签: java class variables static


【解决方案1】:

如果客户端和服务器类在同一个 JVM 中运行,那么您的代码应该可以工作,假设您没有向我们展示的位是正确的。

所以...您(很可能)在一个 JVM 中启动 Client 并在另一个 JVM 中启动 ServerClient.name 静态是不同的。当您在客户端 JVM 中分配一个值时,它不会神奇地传播到服务器 JVM。

【讨论】:

    猜你喜欢
    • 2012-09-06
    • 1970-01-01
    • 2012-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-19
    • 1970-01-01
    • 2014-11-23
    相关资源
    最近更新 更多