封装对象

String[] cols = new String[] { "name", "hobby" };

  Class clz = Class.forName("com.unit.service.approval.Stu");

  Method[] methods = clz.getMethods();

  Object obj = clz.newInstance();

  int i = 0;
  for (String c : cols) {
   i++;
   c = c.substring(0, 1).toUpperCase().concat(
     c.substring(1, c.length()));
   String methodName = "set" + c;
   for (Method m : methods) {
    if (methodName.equals(m.getName())) {
     m.invoke(obj, Integer.toString(i));
    }
   }
  }

  Stu stu = (Stu) obj;

  System.out.println(stu.getName() + "  " + stu.getId() + "  "
    + stu.getHobby());

你可能感兴趣的:(封装对象)