从java中的另一个类获取静态变量 [英] Accesing static variable from another class in java

查看:1272
本文介绍了从java中的另一个类获取静态变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的多线程服务器中,我有一个队列作为链表实现。我想从另一个类访问此队列。两个类都在同一个包中。我试图把这个队列作为public static并通过getter访问它,但没有成功有人告诉我什么是确切的问题。

I had a queue implemented as linked list in my multithreaded server. I want to access this queue from another class. Both classes are in the same package. I tried making this queue as public static and accessing it through getter, but without success Can somebody tell me what is the exact problem.

这是我的代码:
队列声明:

This is my code: Queue Declaration:

public static Queue<Request> q=new ConcurrentLinkedQueue<Request>();

public static void setQ(Queue<Request> q) {
        Connection.q = q;
    }

    public static Queue<Request> getQ() {
        return q;
    }

访问队列:

Queue<Request> queue=new ConcurrentLinkedQueue<Request>(); 
queue=Connection.getQ();

在连接线程中将值添加到队列

Adding Value to Queue in thread of connection

q.add(r);


推荐答案

您可以访问使用符号 ClassName.memberName

public class Foo {
    public static String bar = "hi there";
}

public class Thing {
    public static void main(String[] args) {
        System.out.println(Foo.bar); // "hi there"
   }
}

public static 数据成员通常不是一个好主意(除非他们 final ),但如果你需要一个,那就是你怎么做。

public static data members are usually not a great idea (unless they've final), but if you need one, that's how you do it.

这篇关于从java中的另一个类获取静态变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆