Reputation: 8416
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.
Upvotes: 1
Views: 202
Reputation: 16262
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:
Field hashmapField = clazz.getField("myMap");
//Note, since this is static, we pass it null.
Object fieldValue = hashmapField.get(null);
HashMap<String,String> myMap = (HashMap<String,String>)fieldValue;
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:
public interface StringMappable{
HashMap<String,String> getMap();
}
instead of using reflection.
Upvotes: 5
Reputation: 143886
You want something like this:
public void myfunction(Class clazz)
{
HashMap<String,String> myMap = clazz.getField("myMap").get(null);
}
The Field.get(Object)
method docs say:
If the underlying field is a static field, the obj argument is ignored; it may be null.
And the Class.getField(String)
method docs say:
Returns a Field object that reflects the specified public member field of the class or interface represented by this Class object. The name parameter is a String specifying the simple name of the desired field.
Upvotes: 2