Guest User

Untitled

a guest
Dec 17th, 2017
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.03 KB | None | 0 0
  1. public final class ReflectUtil {
  2.  
  3. /**
  4. * Locates a given field anywhere in the class inheritance hierarchy.
  5. *
  6. * @param instance an object to search the field into.
  7. * @param name field name
  8. * @return a field object
  9. * @throws NoSuchFieldException if the field cannot be located
  10. */
  11. public static Field findField(Object instance, String name) throws NoSuchFieldException {
  12. for (Class<?> clazz = instance.getClass(); clazz != null; clazz = clazz.getSuperclass()) {
  13. try {
  14. Field field = clazz.getDeclaredField(name);
  15.  
  16. if (!field.isAccessible()) {
  17. field.setAccessible(true);
  18. }
  19.  
  20. return field;
  21. } catch (NoSuchFieldException e) {
  22. // ignore and search next
  23. }
  24. }
  25.  
  26. throw new NoSuchFieldException("Field " + name + " not found in " + instance.getClass());
  27. }
  28.  
  29. /**
  30. * Locates a given method anywhere in the class inheritance hierarchy.
  31. *
  32. * @param instance an object to search the method into.
  33. * @param name method name
  34. * @param parameterTypes method parameter types
  35. * @return a method object
  36. * @throws NoSuchMethodException if the method cannot be located
  37. */
  38. public static Method findMethod(Object instance, String name, Class<?>... parameterTypes)
  39. throws NoSuchMethodException {
  40. for (Class<?> clazz = instance.getClass(); clazz != null; clazz = clazz.getSuperclass()) {
  41. try {
  42.  
  43. Method method = clazz.getDeclaredMethod(name, parameterTypes);
  44.  
  45.  
  46. if (!method.isAccessible()) {
  47. method.setAccessible(true);
  48. }
  49.  
  50. return method;
  51. } catch (NoSuchMethodException e) {
  52. // ignore and search next
  53. }
  54. }
  55.  
  56. throw new NoSuchMethodException("Method " + name + " with parameters " +
  57. Arrays.asList(parameterTypes) + " not found in " + instance.getClass());
  58. }
  59. }
Add Comment
Please, Sign In to add comment