Vinetos

Change enum value with Reflection

Apr 21st, 2016
200
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.06 KB | None | 0 0
  1. import java.lang.reflect.Field;
  2.  
  3. public class Main {
  4.  
  5.    
  6.     public static void main(String[] args) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
  7.         for(E e : E.values())
  8.             System.out.println("Color="+e.getColor());
  9.        
  10.         System.out.println("Processing...");
  11.         for(E e : E.values()) {
  12.             if(e != E.BLUE)continue;
  13.             Class<?> c = e.getClass();
  14.            
  15.             Field f = c.getDeclaredField("color");
  16.             f.setAccessible(true);
  17.             f.set(e, "I don't like blue !");
  18.         }
  19.         System.out.println("Done !");
  20.         for(E e : E.values())
  21.             System.out.println("Color="+e.getColor());
  22.        
  23.     }
  24.    
  25. }
  26.  
  27. public enum E {
  28.    
  29.     RED("Rouge"),
  30.     GREEN("Vert"),
  31.     BLUE("Bleu");
  32.    
  33.     private String color;
  34.    
  35.     E(String color) {
  36.         this.color = color;
  37.     }
  38.    
  39.     public String getColor() {
  40.         return this.color;
  41.     }
  42.  
  43. }
  44.  
  45.  
  46. ==========Output:==========
  47. Color=Rouge
  48. Color=Vert
  49. Color=Bleu
  50.  
  51. Processing...
  52. Done !
  53.  
  54. Color=Rouge
  55. Color=Vert
  56. Color=I don't like blue !
Advertisement
Add Comment
Please, Sign In to add comment