两个反射的小例子

  HashMap map = new HashMap();  
 
  Class c = this.getClass();  
 
  // 根据子类声明的field循环取值  
  for (int i = 0; i < c.getDeclaredFields().length; i++) {  
 
   try {  
    // 获取field  
    Field f = c.getDeclaredFields()[i];  
 
    String key = f.getName();  
 
    // 执行对应的get方法  
    String method = "get" + key.substring(0, 1).toUpperCase() + key.substring(1);  
 
    Class pTypes[] = new Class[0];  
 
    Method myMethod = c.getMethod(method, pTypes);  
 
    Object[] arg = new Object[0];  
 
    Object res = myMethod.invoke(this, arg);  
 
    // 保存  
    map.put(key, res);  
 
   } catch (Exception e) {  
    // 返回空  
    return null;  
   }  
  }  
  return map;  






Map hashMap = new HashMap();  
  try {  
   Class c = obj.getClass();  
   Method m[] = c.getDeclaredMethods();  
   for (int i = 0; i < m.length; i++) {  
    if (m[i].getName().indexOf("get")==0) {  
      //System.out.println("方法名:"+m[i].getName());  
     // System.out.println("值:"+ m[i].invoke(obj, new Object[0]));  
     hashMap.put(m[i].getName(), m[i].invoke(obj, new Object[0]));  
    }  
   }  
  } catch (Throwable e) {  
   System.err.println(e);  
  }  
  return hashMap;  

你可能感兴趣的:(C++,c,C#,F#)