예제 #1
0
 /**
  * 循环向上转型, 获取对象的DeclaredField, 并强制设置为可访问.
  *
  * <p>如向上转型到Object仍无法找到, 返回null.
  */
 public static Field getAccessibleField(final Object obj, final String fieldName) {
   Validate.checkNotNull(obj, "object can't be null");
   Validate.checkNotNull(fieldName, "fieldName can't be blank");
   for (Class<?> superClass = obj.getClass();
       superClass != Object.class;
       superClass = superClass.getSuperclass()) {
     try {
       Field field = superClass.getDeclaredField(fieldName);
       makeAccessible(field);
       return field;
     } catch (NoSuchFieldException e) { // NOSONAR
       // Field不在当前类定义,继续向上转型
     }
   }
   return null;
 }
예제 #2
0
  /**
   * 循环向上转型, 获取对象的DeclaredMethod,并强制设置为可访问. 如向上转型到Object仍无法找到, 返回null. 只匹配函数名。
   *
   * <p>用于方法需要被多次调用的情况. 先使用本函数先取得Method,然后调用Method.invoke(Object obj, Object... args)
   */
  public static Method getAccessibleMethodByName(final Object obj, final String methodName) {
    Validate.checkNotNull(obj, "object can't be null");
    Validate.checkNotNull(methodName, "methodName can't be blank");

    for (Class<?> searchType = obj.getClass();
        searchType != Object.class;
        searchType = searchType.getSuperclass()) {
      Method[] methods = searchType.getDeclaredMethods();
      for (Method method : methods) {
        if (method.getName().equals(methodName)) {
          makeAccessible(method);
          return method;
        }
      }
    }
    return null;
  }
예제 #3
0
  /**
   * 循环向上转型, 获取对象的DeclaredMethod,并强制设置为可访问. 如向上转型到Object仍无法找到, 返回null. 匹配函数名+参数类型。
   *
   * <p>用于方法需要被多次调用的情况. 先使用本函数先取得Method,然后调用Method.invoke(Object obj, Object... args)
   */
  public static Method getAccessibleMethod(
      final Object obj, final String methodName, final Class<?>... parameterTypes) {
    Validate.checkNotNull(obj, "object can't be null");
    Validate.checkNotNull(methodName, "methodName can't be blank");

    for (Class<?> searchType = obj.getClass();
        searchType != Object.class;
        searchType = searchType.getSuperclass()) {
      try {
        Method method = searchType.getDeclaredMethod(methodName, parameterTypes);
        makeAccessible(method);
        return method;
      } catch (NoSuchMethodException e) {
        // Method不在当前类定义,继续向上转型
      }
    }
    return null;
  }
예제 #4
0
 public static Class<?> getUserClass(Object instance) {
   Validate.checkNotNull(instance, "Instance must not be null");
   Class<? extends Object> clazz = instance.getClass();
   if (clazz != null && clazz.getName().contains(CGLIB_CLASS_SEPARATOR)) {
     Class<?> superClass = clazz.getSuperclass();
     if (superClass != null && !Object.class.equals(superClass)) {
       return superClass;
     }
   }
   return clazz;
 }