Android 反射工具
来源:互联网 发布:ipad怎么联系淘宝客服 编辑:程序博客网 时间:2024/05/17 02:22
今天给大家介绍一个工具类:反射工具类。
个人觉得这个工具类还是非常方便的,下面有示例。
代码:
public class ReflectUtils { public static Method findMethod(Object instance, String name, Class<?>... parameterTypes) throws NoSuchMethodException { for (Class<?> clazz = instance.getClass(); clazz != null; clazz = clazz.getSuperclass()) { try { Method method = clazz.getDeclaredMethod(name, parameterTypes); if (!method.isAccessible()) { method.setAccessible(true); } return method; } catch (NoSuchMethodException e) { // ignore and search next } } throw new NoSuchMethodException("Method " + name + " with parameters " + Arrays.asList(parameterTypes) + " not found in " + instance.getClass()); } public static Field findField(Object instance, String name) throws NoSuchFieldException { for (Class<?> clazz = instance.getClass(); clazz != null; clazz = clazz.getSuperclass()) { try { Field field = clazz.getDeclaredField(name); if (!field.isAccessible()) { field.setAccessible(true); } return field; } catch (NoSuchFieldException ignore) { } } throw new NoSuchFieldException("Field " + name + " not found in " + instance.getClass()); } public static Field findField(String className, String name) throws NoSuchFieldException, ClassNotFoundException { for (Class<?> clazz = Class.forName(className); clazz != null; clazz = clazz.getSuperclass()) { try { Field field = clazz.getDeclaredField(name); if (!field.isAccessible()) { field.setAccessible(true); } return field; } catch (NoSuchFieldException ignore) { } } throw new NoSuchFieldException("Field " + name + " not found in " + className); }}
示例代码:
private static Field hField; private static Field bField; private static Field aField; private static Field fField; private String getPackageName(AdView adView) { try { if (hField == null) { hField = ReflectUtils.findField(adView, "h"); } Object h = hField.get(adView); if (bField == null) { bField = ReflectUtils.findField("com.f.a", "b"); } HashSet hashSet = (HashSet) bField.get(h); Iterator<String> iterator = hashSet.iterator(); if(iterator.hasNext()) { return iterator.next(); } return null; } catch (Exception ignore) { } return null; }
用最简单的白话总结为:
AdView类中有属性h, H这个类中有属性b, b属性为HashSet ,获取其中的数值。
0 0
- Android 反射工具
- Android 反射工具
- ResUtil~~Android反射工具类
- Android反射工具类ReflectUtil
- 38. Android 反射资源工具ReflectionUtil
- Android反射获取资源 id通用工具类
- android通过反射获取资源ID的工具类
- 工具类-反射工具类
- 反射通用工具类
- Flex反射工具类
- 反射工具类
- java反射工具类
- java反射工具类
- 反射工具类
- Java反射工具类
- Java反射工具类
- JAVA反射工具类
- 反射工具类
- 计算字符串最后一个单词的长度,单词以空格隔开。
- java中10大常见异常
- oracle聚合函数
- Lua 文件处理
- HTTP协议漫谈
- Android 反射工具
- vb 连接 sql 导出数据问题
- 数字通信模型
- MarkdownPad 2 常用快捷键
- script标签写在哪里好?
- I Count Two Three
- 大坝安全监测系统预警值上下限设定
- jgGrid中的editrules使用函数来进行验证
- jqGrid使用setColProp方法动态改变列属性