大家好,又见面了,我是你们的朋友全栈君。
有时候我们只知道一个对象的字段,我们想通过反射的方式将此字段赋值,可直接写反射又太浪费时间,还需要自己手动拼接方法名,而java为我们提供了一个很方便的类(PropertyDescriptor)来操作这一过程。使用很简单,直接看代码:
import com.pibgstar.demo.bean.User;
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/** * @author pibigstar * @create 2018-12-03 18:36 * @desc **/
public class TestPropertyDescriptor {
public static void main(String[] args){
TestPropertyDescriptor test = new TestPropertyDescriptor();
User user = new User();
user.setId("123");
Object id = test.getAttribute("id", user);
System.out.println("id:"+id.toString());
test.setAttribute("name",user,"pibigstar");
System.out.println(user);
}
/** * @Author:pibigstar * @Description: 根据字段获取属性值 */
private Object getAttribute(String filed,Object obj) {
try {
PropertyDescriptor pd = new PropertyDescriptor(filed,obj.getClass());
// 获取getter方法
Method method = pd.getReadMethod();
Object result = method.invoke(obj);
return result;
} catch (IntrospectionException | IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
return null;
}
/** * @Author:pibigstar * @Description: 设置属性字段值 */
private void setAttribute(String filed,Object obj,Object value) {
try {
PropertyDescriptor pd = new PropertyDescriptor(filed,obj.getClass());
// 获取setter方法
Method method = pd.getWriteMethod();
method.invoke(obj, value);
} catch (IntrospectionException | IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
}
}
public class User {
private String id;
private String name;
// setter/getter 方法
}
id:123
User{id='123', name='pibigstar'}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/187273.html原文链接:https://javaforall.cn
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有