@SuppressWarnings("unchecked")
 private T getBean() {
   if (name != null) {
     return (T) beanFactory.getBean(name);
   }
   try {
     return type.newInstance();
   } catch (InstantiationException e) {
     ReflectionUtils.handleReflectionException(e);
   } catch (IllegalAccessException e) {
     ReflectionUtils.handleReflectionException(e);
   }
   // should not happen
   throw new IllegalStateException("Internal error: could not create bean instance for mapping.");
 }
 private Object getPropertyValue(Object bean, String nestedName) {
   BeanWrapperImpl wrapper = new BeanWrapperImpl(bean);
   Object nestedValue = wrapper.getPropertyValue(nestedName);
   if (nestedValue == null) {
     try {
       nestedValue = wrapper.getPropertyType(nestedName).newInstance();
       wrapper.setPropertyValue(nestedName, nestedValue);
     } catch (InstantiationException e) {
       ReflectionUtils.handleReflectionException(e);
     } catch (IllegalAccessException e) {
       ReflectionUtils.handleReflectionException(e);
     }
   }
   return nestedValue;
 }
Beispiel #3
0
  /**
   * 查询一个对象的属性值在数据库中是不是唯一
   *
   * @param entity 实体对象
   * @param propertyNames 属性的名称,可多个 如:"prop1,prop2"
   * @return 针对 编辑 对象保存时 如果和其它 对象 属性名称相同 抛出异常问题 重写此方法
   */
  public boolean isUnique(Object entity, String propertyNames) {
    Class<?> clazz = getTrueClass(entity);
    Criteria criteria = createCriteria(clazz).setProjection(Projections.rowCount());
    String[] nameList = propertyNames.split(",");
    try {
      boolean isQuery = false;
      for (String name : nameList) {
        Object obj = PropertyUtils.getProperty(entity, name);
        if (obj != null) {
          criteria.add(Restrictions.eq(name, obj));
          isQuery = true;
        } else {
          isQuery = false;
        }
      }
      if (!isQuery) {
        return true;
      }

      String idName = getIdName(clazz);
      Serializable id = getId(clazz, entity);
      if (id != null) {
        criteria.add(Restrictions.not(Restrictions.eq(idName, id)));
      }
    } catch (Exception e) {
      ReflectionUtils.handleReflectionException(e);
    }
    this.getSession().evict(entity);
    return (Integer) criteria.uniqueResult() == 0;
  }
  /**
   * This method uses reflection to build a valid hash code.
   *
   * <p>It uses <code>AccessibleObject.setAccessible</code> to gain access to private fields. This
   * means that it will throw a security exception if run under a security manager, if the
   * permissions are not set up correctly. It is also not as efficient as testing explicitly.
   *
   * <p>Transient members will not be used, as they are likely derived fields, and not part of the
   * value of the <code>Object</code>.
   *
   * <p>Static fields will not be tested. Superclass fields will be included.
   *
   * @param obj the object to create a <code>hashCode</code> for
   * @return the generated hash code, or zero if the given object is <code>null</code>
   */
  public static int reflectionHashCode(Object obj) {
    if (obj == null) return 0;

    Class<?> targetClass = obj.getClass();
    if (isArrayOfPrimitives(obj)) {
      // || ObjectUtils.isPrimitiveOrWrapper(targetClass)) {
      return ObjectUtils.nullSafeHashCode(obj);
    }

    if (targetClass.isArray()) {
      return reflectionHashCode((Object[]) obj);
    }

    if (obj instanceof Collection) {
      return reflectionHashCode((Collection<?>) obj);
    }

    if (obj instanceof Map) {
      return reflectionHashCode((Map<?, ?>) obj);
    }

    // determine whether the object's class declares hashCode() or has a
    // superClass other than java.lang.Object that declares hashCode()
    Class<?> clazz = (obj instanceof Class) ? (Class<?>) obj : obj.getClass();
    Method hashCodeMethod = ReflectionUtils.findMethod(clazz, "hashCode", new Class[0]);

    if (hashCodeMethod != null) {
      return obj.hashCode();
    }

    // could not find a hashCode other than the one declared by
    // java.lang.Object
    int hash = INITIAL_HASH;

    try {
      while (targetClass != null) {
        Field[] fields = targetClass.getDeclaredFields();
        AccessibleObject.setAccessible(fields, true);

        for (int i = 0; i < fields.length; i++) {
          Field field = fields[i];
          int modifiers = field.getModifiers();

          if (!Modifier.isStatic(modifiers) && !Modifier.isTransient(modifiers)) {
            hash = MULTIPLIER * hash + reflectionHashCode(field.get(obj));
          }
        }
        targetClass = targetClass.getSuperclass();
      }
    } catch (IllegalAccessException exception) {
      // ///CLOVER:OFF
      ReflectionUtils.handleReflectionException(exception);
      // ///CLOVER:ON
    }

    return hash;
  }
 /**
  * returns the result of {@link BeanUtils#describe(Object)} converted to the proper generic
  * map-type.
  *
  * <p>Exceptions from Reflection are wrapped in {@link IllegalArgumentException}s
  *
  * @throws IllegalArgumentException if some property in the bean cannot be accessed
  */
 @SuppressWarnings("unchecked")
 public static Map<String, String> buildStringAttributeMap(Object bean)
     throws IllegalArgumentException {
   try {
     return BeanUtils.describe(bean);
   } catch (Exception e) {
     ReflectionUtils.handleReflectionException(e);
     throw new IllegalStateException("Should never get here");
   }
 }
 /**
  * Creates a new instance of the beanType and populates it with the property-values from the map
  *
  * @throws IllegalArgumentException if the bean cannot be populated because of errors in the
  *     definition of the beantype
  */
 public static <BeanType> BeanType createBeanFromAttributeMap(
     Class<BeanType> beanType, Map<String, ? extends Object> attributeValues) {
   BeanType instance;
   try {
     instance = beanType.newInstance();
     BeanUtils.populate(instance, attributeValues);
   } catch (Exception e) {
     ReflectionUtils.handleReflectionException(e);
     throw new IllegalStateException("Should never get here");
   }
   return instance;
 }
  /** Init回调函数,初始化一系列泛型参数. */
  public void afterPropertiesSet() {
    // 根据T,反射获得entityClass
    entityClass = GenericsUtils.getSuperClassGenricType(getClass());

    // 根据M,反射获得符合M类型的manager
    List<Field> fields =
        BeanUtils.getFieldsByType(this, GenericsUtils.getSuperClassGenricType(getClass(), 1));
    Assert.isTrue(fields.size() == 1, "subclass's has not only one entity manager property.");
    try {
      entityManager = (M) BeanUtils.forceGetProperty(this, fields.get(0).getName());
      Assert.notNull(entityManager, "subclass not inject manager to action sucessful.");
    } catch (Exception e) {
      ReflectionUtils.handleReflectionException(e);
    }

    // 反射获得entity的主键类型
    try {
      idName = entityManager.getIdName(entityClass);
      idClass = BeanUtils.getPropertyType(entityClass, idName);
    } catch (Exception e) {
      ReflectionUtils.handleReflectionException(e);
    }
  }
Beispiel #8
0
 /**
  * 判断对象某些属性的值在数据库中是否唯一.
  *
  * @param uniquePropertyNames 在POJO里不能重复的属性列表,以逗号分割 如"name,loginid,password"
  */
 public boolean isUnique(T entity, String uniquePropertyNames) {
   Assert.hasText(uniquePropertyNames);
   Criteria criteria = createCriteria().setProjection(Projections.rowCount());
   String[] nameList = uniquePropertyNames.split(",");
   try {
     // 循环加入唯一列
     for (String name : nameList) {
       criteria.add(Restrictions.eq(name, PropertyUtils.getProperty(entity, name)));
     }
     // 以下代码为了如果是update的情况,排除entity自身.
     String idName = getIdName(getEntityClass());
     // 取得entity的主键值
     PK id = getId(getEntityClass(), entity);
     // 如果id!=null,说明对象已存在,该操作为update,加入排除自身的判断
     if (id != null) criteria.add(Restrictions.not(Restrictions.eq(idName, id)));
   } catch (Exception e) {
     ReflectionUtils.handleReflectionException(e);
   }
   return (Integer) criteria.uniqueResult() == 0;
 }
 private Method checkProxy(Method method, Object bean) {
   if (AopUtils.isJdkDynamicProxy(bean)) {
     try {
       // Found a @RabbitListener method on the target class for this JDK proxy ->
       // is it also present on the proxy itself?
       method = bean.getClass().getMethod(method.getName(), method.getParameterTypes());
     } catch (SecurityException ex) {
       ReflectionUtils.handleReflectionException(ex);
     } catch (NoSuchMethodException ex) {
       throw new IllegalStateException(
           String.format(
               "@RabbitListener method '%s' found on bean target class '%s', "
                   + "but not found in any interface(s) for bean JDK proxy. Either "
                   + "pull the method up to an interface or switch to subclass (CGLIB) "
                   + "proxies by setting proxy-target-class/proxyTargetClass "
                   + "attribute to 'true'",
               method.getName(), method.getDeclaringClass().getSimpleName()));
     }
   }
   return method;
 }
Beispiel #10
0
  /**
   * 暴力调用对象函数,忽略private,protected修饰符的限制.
   *
   * @throws NoSuchMethodException 如果没有该Method时抛出.
   */
  @SuppressWarnings("unchecked")
  public static Object invokePrivateMethod(Object object, String methodName, Object... params)
      throws NoSuchMethodException {
    Assert.notNull(object);
    Assert.hasText(methodName);
    Class[] types = new Class[params.length];
    for (int i = 0; i < params.length; i++) {
      types[i] = params[i].getClass();
    }

    Class clazz = object.getClass();
    Method method = null;
    for (Class superClass = clazz;
        superClass != Object.class;
        superClass = superClass.getSuperclass()) {
      try {
        method = superClass.getDeclaredMethod(methodName, types);
        break;
      } catch (NoSuchMethodException e) {
        // 方法不在当前类定义,继续向上转型
      }
    }

    if (method == null)
      throw new NoSuchMethodException("No Such Method:" + clazz.getSimpleName() + methodName);

    boolean accessible = method.isAccessible();
    method.setAccessible(true);
    Object result = null;
    try {
      result = method.invoke(object, params);
    } catch (Exception e) {
      ReflectionUtils.handleReflectionException(e);
    }
    method.setAccessible(accessible);
    return result;
  }
 private static void handleException(Exception e) {
   ReflectionUtils.handleReflectionException(e);
 }
  protected void processScheduled(Scheduled scheduled, Method method, Object bean) {
    try {
      Assert.isTrue(
          void.class.equals(method.getReturnType()),
          "Only void-returning methods may be annotated with @Scheduled");
      Assert.isTrue(
          method.getParameterTypes().length == 0,
          "Only no-arg methods may be annotated with @Scheduled");

      if (AopUtils.isJdkDynamicProxy(bean)) {
        try {
          // Found a @Scheduled method on the target class for this JDK proxy ->
          // is it also present on the proxy itself?
          method = bean.getClass().getMethod(method.getName(), method.getParameterTypes());
        } catch (SecurityException ex) {
          ReflectionUtils.handleReflectionException(ex);
        } catch (NoSuchMethodException ex) {
          throw new IllegalStateException(
              String.format(
                  "@Scheduled method '%s' found on bean target class '%s' but not "
                      + "found in any interface(s) for a dynamic proxy. Either pull the "
                      + "method up to a declared interface or switch to subclass (CGLIB) "
                      + "proxies by setting proxy-target-class/proxyTargetClass to 'true'",
                  method.getName(), method.getDeclaringClass().getSimpleName()));
        }
      } else if (AopUtils.isCglibProxy(bean)) {
        // Common problem: private methods end up in the proxy instance, not getting delegated.
        if (Modifier.isPrivate(method.getModifiers())) {
          LogFactory.getLog(ScheduledAnnotationBeanPostProcessor.class)
              .warn(
                  String.format(
                      "@Scheduled method '%s' found on CGLIB proxy for target class '%s' but cannot "
                          + "be delegated to target bean. Switch its visibility to package or protected.",
                      method.getName(), method.getDeclaringClass().getSimpleName()));
        }
      }

      Runnable runnable = new ScheduledMethodRunnable(bean, method);
      boolean processedSchedule = false;
      String errorMessage =
          "Exactly one of the 'cron', 'fixedDelay(String)', or 'fixedRate(String)' attributes is required";

      // Determine initial delay
      long initialDelay = scheduled.initialDelay();
      String initialDelayString = scheduled.initialDelayString();
      if (StringUtils.hasText(initialDelayString)) {
        Assert.isTrue(initialDelay < 0, "Specify 'initialDelay' or 'initialDelayString', not both");
        if (this.embeddedValueResolver != null) {
          initialDelayString = this.embeddedValueResolver.resolveStringValue(initialDelayString);
        }
        try {
          initialDelay = Integer.parseInt(initialDelayString);
        } catch (NumberFormatException ex) {
          throw new IllegalArgumentException(
              "Invalid initialDelayString value \""
                  + initialDelayString
                  + "\" - cannot parse into integer");
        }
      }

      // Check cron expression
      String cron = scheduled.cron();
      if (StringUtils.hasText(cron)) {
        Assert.isTrue(initialDelay == -1, "'initialDelay' not supported for cron triggers");
        processedSchedule = true;
        String zone = scheduled.zone();
        if (this.embeddedValueResolver != null) {
          cron = this.embeddedValueResolver.resolveStringValue(cron);
          zone = this.embeddedValueResolver.resolveStringValue(zone);
        }
        TimeZone timeZone;
        if (StringUtils.hasText(zone)) {
          timeZone = StringUtils.parseTimeZoneString(zone);
        } else {
          timeZone = TimeZone.getDefault();
        }
        this.registrar.addCronTask(new CronTask(runnable, new CronTrigger(cron, timeZone)));
      }

      // At this point we don't need to differentiate between initial delay set or not anymore
      if (initialDelay < 0) {
        initialDelay = 0;
      }

      // Check fixed delay
      long fixedDelay = scheduled.fixedDelay();
      if (fixedDelay >= 0) {
        Assert.isTrue(!processedSchedule, errorMessage);
        processedSchedule = true;
        this.registrar.addFixedDelayTask(new IntervalTask(runnable, fixedDelay, initialDelay));
      }
      String fixedDelayString = scheduled.fixedDelayString();
      if (StringUtils.hasText(fixedDelayString)) {
        Assert.isTrue(!processedSchedule, errorMessage);
        processedSchedule = true;
        if (this.embeddedValueResolver != null) {
          fixedDelayString = this.embeddedValueResolver.resolveStringValue(fixedDelayString);
        }
        try {
          fixedDelay = Integer.parseInt(fixedDelayString);
        } catch (NumberFormatException ex) {
          throw new IllegalArgumentException(
              "Invalid fixedDelayString value \""
                  + fixedDelayString
                  + "\" - cannot parse into integer");
        }
        this.registrar.addFixedDelayTask(new IntervalTask(runnable, fixedDelay, initialDelay));
      }

      // Check fixed rate
      long fixedRate = scheduled.fixedRate();
      if (fixedRate >= 0) {
        Assert.isTrue(!processedSchedule, errorMessage);
        processedSchedule = true;
        this.registrar.addFixedRateTask(new IntervalTask(runnable, fixedRate, initialDelay));
      }
      String fixedRateString = scheduled.fixedRateString();
      if (StringUtils.hasText(fixedRateString)) {
        Assert.isTrue(!processedSchedule, errorMessage);
        processedSchedule = true;
        if (this.embeddedValueResolver != null) {
          fixedRateString = this.embeddedValueResolver.resolveStringValue(fixedRateString);
        }
        try {
          fixedRate = Integer.parseInt(fixedRateString);
        } catch (NumberFormatException ex) {
          throw new IllegalArgumentException(
              "Invalid fixedRateString value \""
                  + fixedRateString
                  + "\" - cannot parse into integer");
        }
        this.registrar.addFixedRateTask(new IntervalTask(runnable, fixedRate, initialDelay));
      }

      // Check whether we had any attribute set
      Assert.isTrue(processedSchedule, errorMessage);
    } catch (IllegalArgumentException ex) {
      throw new IllegalStateException(
          "Encountered invalid @Scheduled method '" + method.getName() + "': " + ex.getMessage());
    }
  }