daily pastebin goal
76%
SHARE
TWEET

Untitled

a guest Dec 7th, 2017 53 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. public class SomeService {
  2.  
  3.     private Number number = new Integer(0);
  4. }
  5.    
  6. Field field = MealService.class.getDeclaredField("number");    
  7. field.setAccessible(true);
  8. System.out.println("impl:"+field.getType());
  9.    
  10. field.getType() returns the declared type.
  11.    
  12. import java.lang.reflect.Field;
  13.  
  14.     public class InstanceTypeInfo {
  15.         private Number num = new Integer(0);
  16.  
  17.     public static void main(String[] args) throws SecurityException,
  18.             NoSuchFieldException, IllegalArgumentException,
  19.             IllegalAccessException {
  20.         InstanceTypeInfo dI = new InstanceTypeInfo();
  21.         Field field = dI.getClass().getDeclaredField("num");
  22.         System.out.println("Instance Type :" + field.get(dI).getClass());
  23.         System.out.println("Decleration Type:" + field.getType());
  24.     }
  25.  }
  26.    
  27. public class SomeService {
  28.     private Number number = new Integer(0);
  29.     private void setNumber(Number number){
  30.         this.number = number;
  31.     }
  32. }
  33.    
  34. SomeService service = new SomeService();
  35. service.setNumber(new Double(0));//or more vicious : service.setNumber(0.0)
  36.    
  37. Field field = SomeService.class.getDeclaredField("number");    
  38. field.setAccessible(true);
  39. Object value = field.get(service);
  40. if(value instanceof Integer){
  41.     Integer intValue = (Integer)value;
  42. }
RAW Paste Data
Top