2

I am trying to create a map from all the attributes that a class have.My class looks like :

public class MyInventory
{
   private int tiers = 80;
   private int stearing =135;
   private int battery = 46;

 }

Now I have collected all the methods that the class has as :

Field[] fields = this.getClass().getDeclaredFields();

Now , I am trying to create a Map out of it where keys are the values of the fields and the values are the name of the fields. Example :

Map<46,battery> ...etc

Is there a way to do it? The attribute values for the above mentioned class were generated by mapping to properties file and by using spring annotation @ConfigurationProperties. Now I need to create the Map but keys the values of the attributes. I tried to use reflect. However did not find a way to get the value of the fields.

Thanks

7
  • 2
    So you want to create a Map<int,String> - what's the issue? Commented Oct 12, 2018 at 3:30
  • It sound strange, we often create key by field name not vice versa. Anyway, it's possible. Just use reflect api docs.oracle.com/javase/7/docs/api/java/lang/reflect/Field.html Commented Oct 12, 2018 at 3:36
  • @BalwinderSingh Map<Integer, String> * ;) Commented Oct 12, 2018 at 3:38
  • @Eng.Fouad true. Typed in hurry I suppose ;) Commented Oct 12, 2018 at 3:47
  • Why in the world would you need a map if you already have your class done? Wouldn't it be simpler if you work with a list of MyInventory? Commented Oct 12, 2018 at 4:25

4 Answers 4

2

You can use Introspector class.

public Map<Object, String> populateMap(final Object o) throws Exception {
  Map<Object, String> result = new HashMap<>();
  for (PropertyDescriptor pd : Introspector.getBeanInfo(o.getClass()).getPropertyDescriptors()) {
    String fieldName = pd.getName();
    if("class".equals(fieldName) continue;
    Object value = pd.getReadMethod().invoke(o);
    result.put(value, fieldName);
  }
  return result;
}

You can call the above method, passing your class as argument.

MyInventory mi = new MyInventory();
// Sets the properties of mi
mi.setXXX...
// Populates map
populateMap(mi);
Sign up to request clarification or add additional context in comments.

1 Comment

I am getting :Exception in thread "main" java.lang.ClassCastException: java.lang.Class cannot be cast to java.lang.Integer
2
  Map<Integer, String> map() throws IllegalArgumentException, IllegalAccessException {

       Field[] fields = getClass().getDeclaredFields();
       Map<Integer,String> map = new HashMap<>();
       for (Field field : fields) {
           map.put(field.getInt(this), field.getName());
       }
       return map;
   }

Of course it will not map properly if different fields have the same value.

Comments

1

I think, you can have getter method in your class

public class MyInventory
{
   private int tiers = 80;
   private int stearing =135;
   private int battery = 46;

   public int getBattery()
   {
       return battery;
   }
  //and other getter 
 }

and then you can populate your map as

map.put(inventory.getBattery(),"battery");

Because, when you have value, which means you know what is the type for which you are populating map.

Comments

0

You can use json parser. For example jackson:

  import com.fasterxml.jackson.databind.ObjectMapper;
  ... 
  ObjectMapper mapper = new ObjectMapper();
  return mapper.readValue(mapper.writeValueAsString(fooOject), HashMap.class);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.