I’d like to access a static HashMap object on one of my classes. This psuedocode illustrates how I’m attempting to go about it.
public Class A
{
public static HashMap<String,String> myMap;
static
{
myMap.put("my key", "my value");
}
}
...
public void myfunction(Class clazz)
{
HashMap<String,String> myMap = clazz.getThatStaticMap();
}
...
myFunction(A.getClass());
The call to getThatStaticMap() is the part I don’t know how to do.
In my actual code, I’m calling myfunction with a class as a parameter and returning an ArrayList of objects created using the class’s newInstance() method but I want access to that static data belonging to the class to configure each instance.
If I’m understanding you correctly, you want to use reflection to access the field. You can use Class#getField or Class#getDeclaredField to access the map, like this:
However, if you have several classes that are going to have a “myMap” field, you may consider refactoring your code to have an interface like this:
instead of using reflection.