Michael_user3015308
Michael_user3015308

Reputation: 45

String values of field constants in java

Is there any way of getting a string representation of the constant field value from the int value?

For example java.util.Calendar declares several field values such as
public final static int AUGUST = 7;

It there any way to get this information into a Map<Integer, String> containing for instance <7,"AUGUST">`, etc.

P.S. This isn't my class so I can't use ENUMs. And I'm showing Calendar as an example.

Upvotes: 1

Views: 180

Answers (3)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476584

You can use reflection. For instance say Foo is the class, you can get the fields by using:

Foo.class.getDeclaredFields();

You can then iterate over the several fields and use Field.getName() and Field.get(null) to achieve the value.

For instance, say Foo has the following definition:

public class Foo {

    public static final int JANUARY = 1;
    public static final int FEBRUARY = 2;

}

You can run the following code:

 HashMap<Object,String> map = new HashMap<>();

 for (Field f : Foo.class.getDeclaredFields()) {
     try {
     int modifiers = field.getModifiers();//check if the field is public and static
     if (Modifier.isPublic(modifiers) && Modifier.isStatic(modifiers)) {
         if (f.get(null) != null) {
             map.put(f.get(null),f.getName());
         }
     } catch (Throwable t) {
     }
 }

This will result in a HashMap containing <1,"JANUARY"> and <2,"FEBRUARY">.

Upvotes: 1

christopher
christopher

Reputation: 27346

There IS a Reflection based solution to this, but I feel that you should avoid Reflection where possible. One option is to take the good ol' manual approach..

Map<Integer, String> values = HashMap<Integer, String>();

values.put(1, "JANUARY");

// You get the idea.

Yes, this isn't as cool, but it gets the job done without calls to Reflection, and given that you appear to be a beginner programmer, I would avoid Reflection until you're completely, 100% confident.

Upvotes: 1

Marco13
Marco13

Reputation: 54639

While technically this is possible, with reflection and by using Class#getDeclaredFields(), the fact that you asked this is enough of an indication that you should not use it.

Upvotes: -1

Related Questions