2015-03-13 11:59

[Java] Reflection 筆記

  1. @SuppressWarnings("unused") 
  2. Object obj = new Object() { 
  3.    String id = "123"; 
  4.    public String name = "Jax"; 
  5. }; 
  6.  
  7. Class<?> cl = obj.getClass(); 
  8.  
  9. for (Field field : cl.getFields()) { 
  10.    System.out.printf("%s = %s {%s}\n", 
  11.        field.getName(), field.get(obj), field.getType()); 
  12. } 
  13.  
  14. System.out.println("======================="); 
  15.  
  16. for (Field field : cl.getDeclaredFields()) { 
  17.    System.out.printf("%s = %s {%s}\n", 
  18.        field.getName(), field.get(obj), field.getType()); 
  19. } 

Output:
  1. name = Jax {class java.lang.String} 
  2. ======================= 
  3. id = 123 {class java.lang.String} 
  4. name = Jax {class java.lang.String} 

0 回應: