当前位置: 移动技术网 > IT编程>开发语言>Java > java反射获取一个object属性值代码解析

java反射获取一个object属性值代码解析

2019年07月19日  | 移动技术网IT编程  | 我要评论

有些时候你明明知道这个object里面是什么,但是因为种种原因,你不能将它转化成一个对象,只是想单纯地提取出这个object里的一些东西,这个时候就需要用反射了。

假如你这个类是这样的:

private class user {
	string username;
	string userpassword;
	public string getusername() {
		return username;
	}
	public void setusername(string username) {
		this.username = username;
	}
	public string getuserpassword() {
		return userpassword;
	}
	public void setuserpassword(string userpassword) {
		this.userpassword = userpassword;
	}
}

我们new一个,赋值,向上转型为object

user user = new user();
user.setusername("徐风来");
user.setuserpassword("1596666");
object object = user;

获取属性名,用一个数组保存起来

java.lang.reflect.field[] fields = object.getclass().getdeclaredfields();
for (java.lang.reflect.field f : fields) {
  log.i("xbh", f.getname());
}

输出

12-17 12:02:10.199 22949-22949/com.example.wechat i/xbh: this$0
12-17 12:02:10.199 22949-22949/com.example.wechat i/xbh: username
12-17 12:02:10.199 22949-22949/com.example.wechat i/xbh: userpassword
12-17 12:02:10.199 22949-22949/com.example.wechat i/xbh: $change
12-17 12:02:10.199 22949-22949/com.example.wechat i/xbh: serialversionuid

可以看到出现了我们定义的两个属性名了,另外3个自带的别管了

获取属性值,先获取get方法,再通过调用get方法去取

java.lang.reflect.method[] method = object.getclass().getdeclaredmethods();//获取所有方法
for(java.lang.reflect.method m:method) {
  system.<em>out</em>.println(m.getname());
  if (m.getname().startswith("get")) {
    object o = null;
    try {
      o = m.invoke(object);
    } catch (illegalaccessexception | invocationtargetexception e) {
      e.printstacktrace();
    }
    if (o != null && !"".equals(o.tostring())) {
      log.i("xbh", o.tostring());
    }
  }

输出
12-17 12:09:33.429 29677-29677/com.example.wechat i/xbh: 徐风来
12-17 12:09:33.429 29677-29677/com.example.wechat i/xbh: 1596666

那个if语句就是获取get开头的方法

try里面的invoke就是执行这个方法,把返回值放到o里

不通过get方法来获取属性值

java.lang.reflect.field fi = null;
//获取属性
try {
	fi = object.getclass().getdeclaredfield("username");
}
catch (nosuchfieldexception e) {
	e.printstacktrace();
}
fi.setaccessible(true);
//设置当前对象对model私有属性的访问权限
try {
	log.i("xbh", fi.get(object).tostring());
}
catch (illegalaccessexception e) {
	e.printstacktrace();
}

输出
12-17 12:17:34.419 4732-4732/com.example.wechat i/xbh: 徐风来

直接通过getdeclaredfield方法就可以获取(注意和上面的getdeclaredfields方法区分)。但是如果你这个属性是私有的,你肯定就访问不到,所以这里把这个属性设置为public(setaccessible)就可以访问了。

此外如果你获取的是json数据,想解析里面的1个对象不必了,直接转型成map就可以了。

比如

{"code":0,"list":[{"username":"3294727437","userpassword":"xbh1","useravatar":"https://img1.imgtn.bdimg.com/it/u\u003d37460727\u0026gp\u003d0.jpg"}]}

你通过jsonarray(“list”)获取了后面的集合,再通过get(i)获取了单个的对象。其实一开始的对象是被转成map了,仔细看看是不是。所以不需要反射获取属性了,直接转型成map就可以取数据了。

map<string, string=""> map = (map<string, string="">) u;
map.get("useravatar");</string,></string,>

总结

以上就是本文关于java反射获取一个object属性值代码解析的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网