/** * `使用反射机制调用方法` * * @param methodName Method name * @param obj Object holder of the method * @param paraType Array of parameter types * @param paraValue Array of parameters * @return Returned object of the method */ public static Object call(String methodName, Object obj, Class[] paraType, Object[] paraValue) { try { Class cls = obj.getClass(); Method method = cls.getDeclaredMethod(methodName, paraType); // invoke() returns the object returned by the // underlying method. // It returns null, if the underlying method returns void. return method.invoke(obj, paraValue); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } }
/** 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()))); }