简体   繁体   中英

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.

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 :

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.

You should be able to access if directly, or using static getter methods...

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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