反射详解四
- 反射的get方法
/* getter方法 o:要操作类的对象 args:属性名 */ public static <T> T getXxx(T o,String args) throws NoSuchFieldException { Class cls = o.getClass(); //判断该属性是否存在 Field field = field = cls.getDeclaredField(args); if(field == null){ field = cls.getField(args); } if(field == null){ return null; } String fieldName = "get"+args.substring(0,1).toUpperCase()+(args.length()>1?args.substring(1):""); Method method = null; try { method = cls.getMethod(fieldName); return (T)method.invoke(o); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } return null; }
- 反射的set方法
/* setter方法 o:要操作类的对象 args:属性名 attributeValue:属性值 */ public static void setXxx(Object o,String args,Object attributeValue){ Class cls = o.getClass(); //判断该属性是否存在 Field field = null; try { field = cls.getDeclaredField(args); if(field == null){ field = cls.getField(args); } if(field == null){ return; } } catch (NoSuchFieldException e) { e.printStackTrace(); } String fieldName = "set"+args.substring(0,1).toUpperCase()+(args.length()>1?args.substring(1):""); Method method = null; try { method = cls.getMethod(fieldName,attributeValue.getClass()); method.invoke(o,attributeValue); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } }
- 反射的相关方法
getName():获得类的完整名字。 newInstance():通过类的不带参数的构造方法创建这个类的一个对象。 getFields():获得类的public类型的属性。 getDeclaredFields():获得类的所有属性。 getMethods():获得类的public类型的方法。 getDeclaredMethods():获得类的所有方法。 getMethod(String name, Class[] parameterTypes):获得类的特定方法。 getModifiers()和Modifier.toString():获得属修饰符,例如private,public,static等 getReturnType():获得方法的返回类型 getParameterTypes():获得方法的参数类型 getConstructors():获得类的public类型的构造方法。 getConstructor(Class[] parameterTypes):获得类的特定构造方法。 getSuperclass():获取某类的父类 getInterfaces():获取某类实现的接口
- 获取权限名
Modifier.toString(field.getModifiers())
Modifier.toString(method.getModifiers())
getFields() 只能获取public的字段,包括父类的。
getDeclaredFields() 只能获取自己声明的各种字段,包括public,protected,private。
getFields()和 getDeclaredFields(),返回的都是Field对象,获取名称直接field.getName(), 但是属性值则是field.get(Object),这个object是该field所属的!!!
故乡明
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 25岁的心里话