mercredi 15 janvier 2020

Iterating through a hashmap and changing the values using reflection

So I'm coding a gene algorithm and ideally I start off by placing some float variables in a hashmap. These will be the genes that are passed on to different objects.

ie

genes.put("mass", 200);
genes.put("lifespan",0);
genes.put("intelligence",0);
genes.put("dexterity",0);
genes.put("endurance",0);

then later I want hashmap values to be updated when there is a change in the variable. This is the code I have so far;

if(updategenes){

  for ( String key : genes.keySet() ) {
      System.out.println( key );
      try{
     String a = key;
     Field field = a.getClass().getField(key); 
     genes.put(key,field);

     }catch (NoSuchFieldException e) {
     }catch (IllegalAccessException e) {
     }}
  updategenes = false;
}

only issue is it wont accept field as an int even though thats the only possible type that could ever be in field at the time. Any suggestions?





Aucun commentaire:

Enregistrer un commentaire