`
cyhmna
  • 浏览: 33195 次
  • 性别: Icon_minigender_1
  • 来自: 武汉
社区版块
存档分类
最新评论

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为这两个函数所在的类的实例。
0
6
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics