简体   繁体   English

从java中的另一个类访问静态变量

[英]Accesing static variable from another class in java

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. 我尝试将此队列作为公共静态并通过getter访问它,但没有成功可以有人告诉我究竟是什么问题。

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;
    }

Accesing Queue: 访问队列:

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

Adding Value to Queue in thread of connection 在连接线程中向队列添加值

q.add(r);

You can access a public static member of another class directly, using the notation ClassName.memberName : 您可以使用符号ClassName.memberName直接访问另一个类的public static成员:

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 data members are usually not a great idea (unless they've final ), but if you need one, that's how you do it. public static数据成员通常不是一个好主意(除非他们是final ),但如果你需要一个,那就是你如何做到的。

You should be able to access if directly, or using static getter methods... 您应该能够直接访问,或使用静态getter方法...

If this is your Queue class... 如果这是你的队列类......

public class Queue {
    public static LinkedList myList = new LinkedList();

    public static ListedList getMyList(){
        return myList;
    }
}

Then you could access your list be either calling Queue.myList or Queue.getMyList() - both will do the same thing. 然后你可以访问你的列表,调用Queue.myListQueue.getMyList() - 两者都会做同样的事情。 The benefit of using a getter method would be that you can control access to the list, such as by making the method synchronized , preventing calls to the list being out of order. 使用getter方法的好处是您可以控制对列表的访问,例如通过使方法synchronized ,防止对列表的调用乱序。

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

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