Ejemplo n.º 1
0
 /**
  * `获取给定对象的属性的值` `@param fieldName 属性名` `@param obj 对象`
  *
  * @return
  */
 public static Object getFieldValue(String fieldName, Object obj) {
   try {
     Class cls = obj.getClass();
     Field field = cls.getDeclaredField(fieldName);
     return field.get(obj);
   } catch (Exception e) {
     e.printStackTrace();
     print("Field access error!");
     throw new RuntimeException(e);
   }
 }
Ejemplo n.º 2
0
 /** Reflect operations demo */
 public static void reflect(Object obj) {
   // `cls用于描述对象所属的类`
   Class cls = obj.getClass();
   print("Class Name: " + cls.getCanonicalName());
   // `fields包含对象的所有属性`
   Field[] fields = cls.getDeclaredFields();
   print("List of fields:");
   for (Field f : fields) {
     print(String.format("%30s %15s", f.getType(), f.getName()));
   }
   // `methods包含对象的所有方法`
   Method[] methods = cls.getDeclaredMethods();
   print("List of methods:");
   for (Method m : methods)
     print(
         String.format(
             "%30s %15s %30s",
             m.getReturnType(), m.getName(), Arrays.toString(m.getParameterTypes())));
   Constructor[] constructors = cls.getConstructors();
   print("List of contructors:");
   for (Constructor c : constructors)
     print(String.format("%30s %15s", c.getName(), Arrays.toString(c.getParameterTypes())));
 }