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
原创粉丝点击