How to access static block variables outside of class in java

1.9k Views Asked by At

I was working on some code in which I need to access the variable "hs" present in the static block of one class from another. Note: Both the class are preset in different packages.

Code is as follow:

public class A{
    static {
        HashSet<String> hs = new HashSet<>();
    }
}

I Googled about it but nothing found anything helpful. Your help would be very appreciable.

EDIT: I am not allowed to make changes in this file still need to access it from the other file.

Why I need to do this cause I am doing unit testing by JUnit and there is nothing what this block is returning which I can put assertEquals() on. So the option I left with is to test the side-effects and this variable "hs" value is getting changed as a side-effect. That's why I need to access it from another file.

2

There are 2 best solutions below

2
Ryuzaki L On

Declare it as public static inside the class and initialize it in static block

class A1{
public static HashSet<String> hs;
static {
     hs= new HashSet<>();
    }
 }
0
Harshit Suhagiya On

Need create getter and setter for variable "hs".

Class 1:

public class Test {

    public static HashSet<String> hs;

    static {
        hs = new HashSet<>();
        hs.add("Test14");
        hs.add("Test15");
        hs.add("Test16");
    }

    public static HashSet<String> getHs() {
        return hs;
    }

    public static void setHs(HashSet<String> hs) {
        Test.hs = hs;
    }


}

Class 2

If you need to use "hs" variable in without static method then:

public class Test2 {

    public void test() {
        Test ts = new Test();
        ts.getHs();
    }
}

If you need to use "hs" variable in with static method then:

public class Test2 {

    public static void test() {
        Test.getHs();
    }
}