博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

原理:Java的反射能够获取属性的名称,然后通过invoke调用类的某个方法。

比如有个属性叫userName,这个类写了个方法叫getUserName,通过invoke调用getUserName这个方法。

 

代码如下

 

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class ParameterBase
{
    
/**
     * Get Class field and value Map
     * 
@return
     
*/
    
public Map<String, String> getClassInfo()
    {
        Map
<String ,String>  fieldsAndValues = new HashMap<String, String>();
        Field [] fields 
= this.getClass().getDeclaredFields();
        
for(int i=0; i< fields.length; i++)
        {
            Field f 
= fields[i];
            String value 
= getFieldValue(this ,f.getName()).toString();
            fieldsAndValues.put(f.getName(),value);
        } 
      
return fieldsAndValues;
    }  
    
    
    
    
private  String getFieldValue(Object owner, String fieldName)
    {
        
return invokeMethod(owner, fieldName,null).toString();
    }
    
    
    
/**
     * 
     * 执行某个Field的getField方法
     * 
     * 
@param owner 类
     * 
@param fieldName 类的属性名称
     * 
@param args 参数,默认为null
     * 
@return 
     
*/
    
private   Object invokeMethod(Object owner, String fieldName, Object[] args)
    {
        Class
<? extends Object> ownerClass = owner.getClass();
        
        
//fieldName -> FieldName  
        String methodName = fieldName.substring(01).toUpperCase()+ fieldName.substring(1);
        
        Method method 
= null;
        
try 
        {
            method 
= ownerClass.getMethod("get" + methodName);
        } 
        
catch (SecurityException e) 
        {

            
//e.printStackTrace();
        } 
        
catch (NoSuchMethodException e) 
        {
            
// e.printStackTrace();
            return "";
        }
        
        
//invoke getMethod
        try
        {
            
return method.invoke(owner);
        } 
        
catch (Exception e)
        {
            
return "";
        }
    }
}

 

 写一个类User继承于ParameterBase并写上一个测试代码

public class User extends ParameterBase
{
    String userName ;
    String passWorld;
    
public String getUserName()
    {
        
return userName;
    }
    
public void setUserName(String userName)
    {
        
this.userName = userName;
    }
    
public String getPassWorld()
    {
        
return passWorld;
    }
    
public void setPassWorld(String passWorld)
    {
        
this.passWorld = passWorld;
    }
    
    
public static void main(String[] args)
    {
        User u 
= new  User();
        u.passWorld 
= "123";
        u.userName 
= "aaaaa";
        System.out.println(u.getClassInfo().toString());
        
    }
}

 程序输出

{passWorld=123, userName=aaaaa}
posted on 2011-04-09 23:04  Likwo  阅读(13959)  评论(1编辑  收藏  举报