今天给大家介绍一个工具类:反射工具类。
个人觉得这个工具类还是非常方便的,下面有示例。
代码:
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) {
}
}
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);
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
示例代码:
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;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
用最简单的白话总结为:
AdView类中有属性h, H这个类中有属性b, b属性为HashSet ,获取其中的数值。