Java 类org.apache.commons.lang.reflect.ConstructorUtils 实例源码

项目:soundwave    文件:Ec2InstanceUpdateHandler.java   
public Ec2InstanceUpdateHandler(CmdbInstanceStore cmdbStore, CloudInstanceStore cloudStore,
                                DailySnapshotStoreFactory dailySnapshotStoreFactory) {
  this.cmdbInstanceStore = cmdbStore;
  this.cloudInstanceStore = cloudStore;
  this.dailySnapshotStoreFactory = dailySnapshotStoreFactory;
  try {
    String className = Configuration.getProperties().getString("instance_factory",
        "com.pinterest.cmp.soundwave.pinterest.PinterestEsInstanceFactory");
    if (className.isEmpty()) {
      logger.error("instance_factory is not set");
    } else {
      Class factoryClass = Class.forName(className);
      this.esInstanceFactory = (AbstractEsInstanceFactory) ConstructorUtils.invokeConstructor(
          factoryClass, null);
      this.esInstanceFactory.setCloudInstanceStore(this.cloudInstanceStore);
    }
  } catch (Exception ex) {
    logger.error("Class {} cannot be loaded error {}",
        Configuration.getProperties().getString("instance_factory"), ex.getLocalizedMessage());
  }
}
项目:daikon    文件:GatewayOperations.java   
private Object handleCustomExecution(Call callAnnotation, Object[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
    final String[] hystrixBeans = context.getBeanNamesForType(callAnnotation.using());
    if (hystrixBeans.length == 1) {
        final HystrixCommand bean = (HystrixCommand) context.getBean(hystrixBeans[0], args);
        return bean.execute();
    } else {
        final HystrixCommand newInstance = (HystrixCommand) ConstructorUtils.invokeConstructor(callAnnotation.using(), args);
        return newInstance.execute();
    }
}
项目:TOSCAna    文件:TypeWrapper.java   
private static <T> T wrap(MappingEntity entity, Class type) {
    try {
        if (Modifier.isAbstract(type.getModifiers())) {
            type = KeyReflector.detectRealCapabilityType(entity, type);
        }
        T node = (T) ConstructorUtils.invokeConstructor(type, entity);
        return node;
    } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException | InstantiationException e) {
        throw new IllegalStateException(String.format("Failed to wrap up entity '%s' in type '%s'", entity, type), e);
    }
}
项目:kafka-connect-fs    文件:ReflectionUtils.java   
private static <T> T make(Class<T> clazz, Object... args) throws Throwable {
    try {
        Class[] constClasses = Arrays.stream(args).map(arg -> arg.getClass()).toArray(Class[]::new);

        Constructor constructor = ConstructorUtils.getMatchingAccessibleConstructor(clazz, constClasses);
        return (T) constructor.newInstance(args);
    } catch (IllegalAccessException |
            InstantiationException |
            InvocationTargetException e) {
        throw e.getCause();
    }
}
项目:cuba    文件:ReflectionHelper.java   
/**
 * Instantiates an object by appropriate constructor.
 * @param cls       class
 * @param params    constructor arguments
 * @return          created object instance
 * @throws NoSuchMethodException    if the class has no constructor matching the given arguments
 */
@SuppressWarnings("unchecked")
public static <T> T newInstance(Class<T> cls, Object... params) throws NoSuchMethodException {
    Class[] paramTypes = getParamTypes(params);

    Constructor<T> constructor = ConstructorUtils.getMatchingAccessibleConstructor(cls, paramTypes);
    if (constructor == null)
        throw new NoSuchMethodException("Cannot find a matching constructor for " + cls.getName() + " and given parameters");
    try {
        return constructor.newInstance(params);
    } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
        throw new RuntimeException(e);
    }
}
项目:Gobblin    文件:PartitionedDataWriter.java   
public PartitionedDataWriter(DataWriterBuilder<S, D> builder, final State state) throws IOException {

    this.closer = Closer.create();
    this.partitionWriters = CacheBuilder.newBuilder().build(new CacheLoader<GenericRecord, DataWriter<D>>() {
      @Override public DataWriter<D> load(final GenericRecord key) throws Exception {
        return closer
            .register(new InstrumentedPartitionedDataWriterDecorator<D>(createPartitionWriter(key), state, key));
      }
    });

    if(state.contains(ConfigurationKeys.WRITER_PARTITIONER_CLASS)) {
      Preconditions.checkArgument(builder instanceof PartitionAwareDataWriterBuilder,
          String.format("%s was specified but the writer %s does not support partitioning.",
              ConfigurationKeys.WRITER_PARTITIONER_CLASS, builder.getClass().getCanonicalName()));

      try {
        this.shouldPartition = true;
        this.builder = Optional.of(PartitionAwareDataWriterBuilder.class.cast(builder));
        this.partitioner = Optional.of(
            WriterPartitioner.class.cast(ConstructorUtils.invokeConstructor(
                    Class.forName(state.getProp(ConfigurationKeys.WRITER_PARTITIONER_CLASS)), state)));
        Preconditions.checkArgument(
            this.builder.get().validatePartitionSchema(this.partitioner.get().partitionSchema()),
            String.format("Writer %s does not support schema from partitioner %s",
                builder.getClass().getCanonicalName(), this.partitioner.getClass().getCanonicalName()));
      } catch(ReflectiveOperationException roe) {
        throw new IOException(roe);
      }
    } else {
      this.shouldPartition = false;
      InstrumentedDataWriterDecorator<D> writer = this.closer.register(
          new InstrumentedDataWriterDecorator<D>(builder.build(), state));
      this.partitionWriters.put(NON_PARTITIONED_WRITER_KEY,
          writer);
      this.partitioner = Optional.absent();
      this.builder = Optional.absent();
    }
  }
项目:awseb-deployment-plugin    文件:AWSClientFactory.java   
@SuppressWarnings("unchecked")
public <T> T getService(Class<T> serviceClazz)
    throws NoSuchMethodException, IllegalAccessException,
           InvocationTargetException, InstantiationException {

  Class<?> paramTypes[] = new Class<?>[]{AWSCredentialsProvider.class, ClientConfiguration.class};

  ClientConfiguration newClientConfiguration = new ClientConfiguration(this.clientConfiguration);

  if (AmazonS3.class.isAssignableFrom(serviceClazz)) {
    newClientConfiguration = newClientConfiguration.withSignerOverride("AWSS3V4SignerType");
  } else {
    newClientConfiguration = newClientConfiguration.withSignerOverride(null);
  }

  Object params[] = new Object[]{creds, newClientConfiguration};

  T resultObj = (T) ConstructorUtils.invokeConstructor(serviceClazz, params, paramTypes);

  if (DEFAULT_REGION.equals(defaultString(region, DEFAULT_REGION))) {
    return resultObj;
  } else {
    for (ServiceEndpointFormatter formatter : ServiceEndpointFormatter.values()) {
      if (formatter.matches(resultObj)) {
        ((AmazonWebServiceClient) resultObj).setEndpoint(getEndpointFor(formatter));
        break;
      }
    }
  }

  return resultObj;
}
项目:soundwave    文件:ObjectAdapter.java   
public static <T1, T2> T2 getObject(T1 object, Class<T2> adaptedClass) {

    try {
      Map<String, Field> objectFieldsMap = getAllFields(object.getClass());

      T2 adaptedObject = (T2) ConstructorUtils.invokeConstructor(adaptedClass, null);
      List<String> target = getFields(adaptedClass);
      for (String field : target) {

        // get The field of the adapted object
        Field targetField = adaptedClass.getDeclaredField(field);
        targetField.setAccessible(true);

        if (targetField.isAnnotationPresent(NestedField.class)) {

          NestedField annotation = targetField.getDeclaredAnnotation(NestedField.class);
          String[] hierarchy = StringUtils.split(annotation.src(), ".");
          Field nestedField = objectFieldsMap.get(hierarchy[0]);
          nestedField.setAccessible(true);
          Object fieldValue = nestedField.get(object);

          for (int i = 1; i < hierarchy.length; i++) {
            nestedField = nestedField.getType().getDeclaredField(hierarchy[i]);
            nestedField.setAccessible(true);
            fieldValue = nestedField.get(fieldValue);
          }

          // Set the last level value from hierarchy
          targetField.set(adaptedObject, fieldValue);

        } else {

          // Non nested field process as normal
          Field sourceField;
          if (targetField.isAnnotationPresent(StringDate.class)) {

            // Process date fields
            sourceField = objectFieldsMap.get(field);
            sourceField.setAccessible(true);

            if (sourceField.get(object) != null) {

              // Value is not null
              DateTime time = new DateTime(sourceField.get(object), DateTimeZone.UTC);
              targetField.set(adaptedObject, time.toString());
            } else {

              targetField.set(adaptedObject, "");
            }


          } else if (targetField.isAnnotationPresent(IgnoreAdaptation.class)) {
            // Leave field as it is. no processing.
          } else {

            sourceField = objectFieldsMap.get(field);
            sourceField.setAccessible(true);

            targetField.set(adaptedObject, sourceField.get(object));
          }
        }
      }

      return adaptedObject;

    } catch (Exception e) {
      logger.error(ExceptionUtils.getRootCauseMessage(e));
      return null;
    }


  }