Matthew
Matthew

Reputation: 8416

How to access a static member through a Class object

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

Answers (3)

Zach L
Zach L

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

Azder
Azder

Reputation: 4728

From: here and here:

clazz.getField("myMap").get(null)

Upvotes: 3

Jon Lin
Jon Lin

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

Related Questions