java 动态访问Getter和Setter


1,Setter
public static void setValueByAPI(Object API_obj, String API_name, int val) {
Class<?> iClass = API_obj.getClass();
try{
Method setMethod = iClass.getMethod("set" + API_name, new Class[]{int.class});
Log.v(TAG, "setValueByAPI " + API_name + " value:" + val);
setMethod.invoke(API_obj, val);
}catch (Exception e) {
Log.w(TAG, "setValueByAPI reflection exception " + e);
}
    }

2,Getter

public static int getValueByAPI(Object API_obj, String API_name) {
    int retVal = 0;
Class<?> iClass = API_obj.getClass();
try{
Method getMethod = iClass.getMethod("get" + API_name);
retVal = (Integer)getMethod.invoke(API_obj);
Log.v(TAG, "getValueByAPI " + API_name + " return:" + retVal);
}catch (Exception e) {
Log.w(TAG, "getValueByAPI reflection exception " + e);
}
return retVal;
    }

其中,Object API_obj为这两个函数所在的类的实例。

你可能感兴趣的:(java)