react-native-navigation的迁移库

ReflectionUtils.java 1.2KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. package com.reactnativenavigation.utils;
  2. import android.support.annotation.Nullable;
  3. import java.lang.reflect.Field;
  4. public class ReflectionUtils {
  5. public static void setField(Object obj, String name, Object value) {
  6. try {
  7. Field field = getField(obj.getClass(), name);
  8. if (field == null) {
  9. return;
  10. }
  11. field.setAccessible(true);
  12. field.set(obj, value);
  13. } catch (Exception e) {
  14. e.printStackTrace();
  15. }
  16. }
  17. @Nullable
  18. public static Object getDeclaredField(Object obj, String fieldName) {
  19. try {
  20. Field f = getField(obj.getClass(), fieldName);
  21. if (f == null) {
  22. return null;
  23. }
  24. f.setAccessible(true);
  25. return f.get(obj);
  26. } catch (Exception e) {
  27. e.printStackTrace();
  28. }
  29. return null;
  30. }
  31. private static Field getField(Class clazz, String name) {
  32. try {
  33. return clazz.getDeclaredField(name);
  34. } catch (NoSuchFieldException nsfe) {
  35. return getField(clazz.getSuperclass(), name);
  36. } catch (Exception e) {
  37. return null;
  38. }
  39. }
  40. }