Java Code Examples for org.apache.commons.lang3.reflect.ConstructorUtils

The following examples show how to use org.apache.commons.lang3.reflect.ConstructorUtils. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
public LoginCallback create(final Controller controller) {
    try {
        if(null == constructor) {
            constructor = ConstructorUtils.getMatchingAccessibleConstructor(clazz, controller.getClass());
        }
        if(null == constructor) {
            log.warn(String.format("No matching constructor for parameter %s", controller.getClass()));
            // Call default constructor for disabled implementations
            return clazz.newInstance();
        }
        return constructor.newInstance(controller);
    }
    catch(InstantiationException | InvocationTargetException | IllegalAccessException e) {
        log.error(String.format("Failure loading callback class %s. %s", clazz, e.getMessage()));
        return new DisabledLoginCallback();
    }
}
 
Example 2
public AbstractUserDateFormatter create(final String timezone) {
    try {
        if(null == constructor) {
            constructor = ConstructorUtils.getMatchingAccessibleConstructor(clazz, timezone.getClass());
        }
        if(null == constructor) {
            log.warn(String.format("No matching constructor for parameter %s", timezone.getClass()));
            // Call default constructor for disabled implementations
            return clazz.newInstance();
        }
        return constructor.newInstance(timezone);
    }
    catch(InstantiationException | InvocationTargetException | IllegalAccessException e) {
        throw new FactoryException(e.getMessage(), e);
    }
}
 
Example 3
public AlertCallback create(final Controller controller) {
    try {
        if(null == constructor) {
            constructor = ConstructorUtils.getMatchingAccessibleConstructor(clazz, controller.getClass());
        }
        if(null == constructor) {
            log.warn(String.format("No matching constructor for parameter %s", controller.getClass()));
            // Call default constructor for disabled implementations
            return clazz.newInstance();
        }
        return constructor.newInstance(controller);
    }
    catch(InstantiationException | InvocationTargetException | IllegalAccessException e) {
        log.error(String.format("Failure loading callback class %s. %s", clazz, e.getMessage()));
        return new DisabledAlertCallback();
    }
}
 
Example 4
public HostKeyCallback create(final Controller c, final Protocol protocol) {
    if(Scheme.sftp.equals(protocol.getScheme())) {
        try {
            if(null == constructor) {
                constructor = ConstructorUtils.getMatchingAccessibleConstructor(clazz, c.getClass());
            }
            if(null == constructor) {
                log.warn(String.format("No matching constructor for parameter %s", c.getClass()));
                // Call default constructor for disabled implementations
                return clazz.newInstance();
            }
            return constructor.newInstance(c);
        }
        catch(InstantiationException | InvocationTargetException | IllegalAccessException e) {
            log.error(String.format("Failure loading callback class %s. %s", clazz, e.getMessage()));
            return new DisabledHostKeyCallback();
        }
    }
    return new DisabledHostKeyCallback();
}
 
Example 5
Source Project: cyberduck   Source File: VaultFactory.java    License: GNU General Public License v3.0 6 votes vote down vote up
private Vault create(final Path directory, final String masterkey, final byte[] pepper) {
    try {
        final Constructor<Vault> constructor = ConstructorUtils.getMatchingAccessibleConstructor(clazz,
            directory.getClass(), masterkey.getClass(), pepper.getClass());
        if(null == constructor) {
            log.warn(String.format("No matching constructor for parameter %s", directory.getClass()));
            // Call default constructor for disabled implementations
            return clazz.newInstance();
        }
        return constructor.newInstance(directory, masterkey, pepper);
    }
    catch(InstantiationException | InvocationTargetException | IllegalAccessException e) {
        log.error(String.format("Failure loading callback class %s. %s", clazz, e.getMessage()));
        return Vault.DISABLED;
    }
}
 
Example 6
public CertificateTrustCallback create(final Controller controller) {
    try {
        if(null == constructor) {
            constructor = ConstructorUtils.getMatchingAccessibleConstructor(clazz, controller.getClass());
        }
        if(null == constructor) {
            log.warn(String.format("No matching constructor for parameter %s", controller.getClass()));
            // Call default constructor for disabled implementations
            return clazz.newInstance();
        }
        return constructor.newInstance(controller);
    }
    catch(InstantiationException | InvocationTargetException | IllegalAccessException e) {
        log.error(String.format("Failure loading callback class %s. %s", clazz, e.getMessage()));
        return new DisabledCertificateTrustCallback();
    }
}
 
Example 7
Source Project: cyberduck   Source File: ThreadPoolFactory.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * @param size     Maximum pool size
 * @param priority Thread priority
 * @param handler  Uncaught thread exception handler
 */
protected ThreadPool create(final String prefix, final Integer size, final ThreadPool.Priority priority, final Thread.UncaughtExceptionHandler handler) {
    try {
        final Constructor<ThreadPool> constructor = ConstructorUtils.getMatchingAccessibleConstructor(clazz,
            prefix.getClass(), size.getClass(), priority.getClass(), handler.getClass());
        if(null == constructor) {
            log.warn(String.format("No matching constructor for parameter %s", handler.getClass()));
            // Call default constructor for disabled implementations
            return clazz.newInstance();
        }
        return constructor.newInstance(prefix, size, priority, handler);
    }
    catch(InstantiationException | InvocationTargetException | IllegalAccessException e) {
        throw new FactoryException(e.getMessage(), e);
    }
}
 
Example 8
public PasswordCallback create(final Controller controller) {
    try {
        if(null == constructor) {
            constructor = ConstructorUtils.getMatchingAccessibleConstructor(clazz, controller.getClass());
        }
        if(null == constructor) {
            log.warn(String.format("No matching constructor for parameter %s", controller.getClass()));
            // Call default constructor for disabled implementations
            return clazz.newInstance();
        }
        return constructor.newInstance(controller);
    }
    catch(InstantiationException | InvocationTargetException | IllegalAccessException e) {
        log.error(String.format("Failure loading callback class %s. %s", clazz, e.getMessage()));
        return new DisabledPasswordCallback();
    }
}
 
Example 9
public CertificateIdentityCallback create(final Controller controller) {
    try {
        if(null == constructor) {
            constructor = ConstructorUtils.getMatchingAccessibleConstructor(clazz, controller.getClass());
        }
        if(null == constructor) {
            log.warn(String.format("No matching constructor for parameter %s", controller.getClass()));
            // Call default constructor for disabled implementations
            return clazz.newInstance();
        }
        return constructor.newInstance(controller);
    }
    catch(InstantiationException | InvocationTargetException | IllegalAccessException e) {
        log.error(String.format("Failure loading callback class %s. %s", clazz, e.getMessage()));
        return new DisabledCertificateIdentityCallback();
    }
}
 
Example 10
Source Project: codenjoy   Source File: GameServiceImpl.java    License: GNU General Public License v3.0 6 votes vote down vote up
private List<Class> allGames() {
    List<Class> result = new LinkedList<>(
            findInPackage(gamePackage));

    result.sort(Comparator.comparing(Class::getName));

    result.remove(NullGameType.class);
    result.remove(AbstractGameType.class);

    remove(result,
            it -> ConstructorUtils.getMatchingAccessibleConstructor(it) == null);

    if (pluginsEnable) {
        loadFromPlugins(result);
    }

    if (excludeGames != null) {
        remove(result, it -> Stream.of(excludeGames)
                .anyMatch(name -> it.getPackage().toString().contains(name)));
    }

    return result;
}
 
Example 11
Source Project: incubator-gobblin   Source File: DefaultAuditSinkFactory.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Create a new {@link AuditSink} using the alias or cannonical classname specified at {@value #AUDIT_SINK_CLASS_NAME_KEY} in the <code>config</code>
 * The {@link AuditSink} class MUST have an accessible constructor <code>abc(Config config, TableMetadata tableMetadata)</code>
 * <br>
 * If {@value #AUDIT_SINK_CLASS_NAME_KEY} is not set in <code>config</code>, a default {@link #DEFAULT_AUDIT_SINK_CLASS} is used
 *
 * @param config job configs
 * @param auditRuntimeMetadata runtime table metadata
 *
 * @return a new instance of {@link AuditSink}
 */
public AuditSink create(Config config, ValueAuditRuntimeMetadata auditRuntimeMetadata) {

  String sinkClassName = DEFAULT_AUDIT_SINK_CLASS;
  if (config.hasPath(AUDIT_SINK_CLASS_NAME_KEY)) {
    sinkClassName = config.getString(AUDIT_SINK_CLASS_NAME_KEY);
  }
  log.info("Using audit sink class name/alias " + sinkClassName);

  try {
    return (AuditSink)ConstructorUtils.invokeConstructor(Class.forName(this.aliasResolver.resolve(
        sinkClassName)), config, auditRuntimeMetadata);
  } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException | InstantiationException
      | ClassNotFoundException e) {
    throw new RuntimeException(e);
  }
}
 
Example 12
@Override
public Optional<CompactorListener> createCompactorListener(Properties properties)
    throws CompactorListenerCreationException {
  State state = new State(properties);

  if (Strings.isNullOrEmpty(state.getProp(COMPACTOR_LISTENERS))) {
    return Optional.absent();
  }

  List<CompactorListener> listeners = new ArrayList<>();
  for (String listenerClassName : state.getPropAsList(COMPACTOR_LISTENERS)) {
    try {
      listeners.add((CompactorListener) ConstructorUtils
          .invokeConstructor(Class.forName(listenerClassName), properties));
    } catch (ReflectiveOperationException e) {
      throw new CompactorListenerCreationException(String
          .format("Unable to create CompactorListeners from key \"%s\" with value \"%s\"", COMPACTOR_LISTENERS,
              properties.getProperty(COMPACTOR_LISTENERS)), e);
    }
  }
  return Optional.<CompactorListener>of(new SerialCompactorListener(listeners));
}
 
Example 13
Source Project: incubator-gobblin   Source File: GobblinConstructorUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Convenience method on top of {@link ConstructorUtils#invokeConstructor(Class, Object[])} that returns a new
 * instance of the <code>cls</code> based on a constructor priority order. Each {@link List} in the
 * <code>constructorArgs</code> array contains the arguments for a constructor of <code>cls</code>. The first
 * constructor whose signature matches the argument types will be invoked.
 *
 * @param cls the class to be instantiated
 * @param constructorArgs An array of constructor argument list. Order defines the priority of a constructor.
 * @return
 *
 * @throws NoSuchMethodException if no constructor matched was found
 */
@SafeVarargs
public static <T> T invokeFirstConstructor(Class<T> cls, List<Object>... constructorArgs)
    throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {

  for (List<Object> args : constructorArgs) {

    Class<?>[] parameterTypes = new Class[args.size()];
    for (int i = 0; i < args.size(); i++) {
      parameterTypes[i] = args.get(i).getClass();
    }

    if (ConstructorUtils.getMatchingAccessibleConstructor(cls, parameterTypes) != null) {
      return ConstructorUtils.invokeConstructor(cls, args.toArray(new Object[args.size()]));
    }
  }
  throw new NoSuchMethodException("No accessible constructor found");
}
 
Example 14
Source Project: incubator-gobblin   Source File: GobblinConstructorUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns a new instance of the <code>cls</code> based on a set of arguments. The method will search for a
 * constructor accepting the first k arguments in <code>args</code> for every k from args.length to 0, and will
 * invoke the first constructor found.
 *
 * For example, {@link #invokeLongestConstructor}(cls, myString, myInt) will first attempt to create an object with
 * of class <code>cls</code> with constructor <init>(String, int), if it fails it will attempt <init>(String), and
 * finally <init>().
 *
 * @param cls the class to instantiate.
 * @param args the arguments to use for instantiation.
 * @throws ReflectiveOperationException
 */
public static <T> T invokeLongestConstructor(Class<T> cls, Object... args) throws ReflectiveOperationException {

  Class<?>[] parameterTypes = new Class[args.length];
  for (int i = 0; i < args.length; i++) {
    parameterTypes[i] = args[i].getClass();
  }

  for (int i = args.length; i >= 0; i--) {
    if (ConstructorUtils.getMatchingAccessibleConstructor(cls, Arrays.copyOfRange(parameterTypes, 0, i)) != null) {
      log.debug(
          String.format("Found accessible constructor for class %s with parameter types %s.", cls,
              Arrays.toString(Arrays.copyOfRange(parameterTypes, 0, i))));
      return ConstructorUtils.invokeConstructor(cls, Arrays.copyOfRange(args, 0, i));
    }
  }
  throw new NoSuchMethodException(String.format("No accessible constructor for class %s with parameters a subset of %s.",
      cls, Arrays.toString(parameterTypes)));
}
 
Example 15
Source Project: incubator-gobblin   Source File: PusherFactory.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public SharedResourceFactoryResponse<Pusher<T>> createResource(SharedResourcesBroker<S> broker,
    ScopedConfigView<S, StringNameSharedResourceKey> config)
    throws NotConfiguredException {
  Config pusherConfig = config.getConfig().withFallback(FALLBACK);
  String pusherClass = pusherConfig.getString(PUSHER_CLASS);

  Pusher<T> pusher;
  try {
    pusher = (Pusher) ConstructorUtils.invokeConstructor(Class.forName(pusherClass), pusherConfig);
  } catch (ReflectiveOperationException e) {
    log.warn("Unable to construct a pusher with class {}. LoggingPusher will be used", pusherClass, e);
    pusher = new LoggingPusher<>();
  }
  return new ResourceInstance<>(pusher);
}
 
Example 16
@SuppressWarnings("unchecked")
public static KafkaSchemaRegistry getSchemaRegistry(Properties props) {
  Preconditions.checkArgument(props.containsKey(KafkaSchemaRegistryConfigurationKeys.KAFKA_SCHEMA_REGISTRY_CLASS),
      "Missing required property " + KafkaSchemaRegistryConfigurationKeys.KAFKA_SCHEMA_REGISTRY_CLASS);

  boolean tryCache = Boolean.parseBoolean(props.getProperty(KafkaSchemaRegistryConfigurationKeys.KAFKA_SCHEMA_REGISTRY_CACHE,
      DEFAULT_TRY_CACHING));

  Class<?> clazz;
  try {
    clazz =
        (Class<?>) Class.forName(props.getProperty(KafkaSchemaRegistryConfigurationKeys.KAFKA_SCHEMA_REGISTRY_CLASS));
    KafkaSchemaRegistry schemaRegistry = (KafkaSchemaRegistry) ConstructorUtils.invokeConstructor(clazz, props);
    if (tryCache && !schemaRegistry.hasInternalCache())
    {
      schemaRegistry = new CachingKafkaSchemaRegistry(schemaRegistry);
    }
    return schemaRegistry;
  } catch (ClassNotFoundException | NoSuchMethodException | IllegalAccessException | InvocationTargetException
      | InstantiationException e) {
    log.error("Failed to instantiate " + KafkaSchemaRegistry.class, e);
    throw Throwables.propagate(e);
  }
}
 
Example 17
Source Project: incubator-gobblin   Source File: HiveSerDeManager.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Get an instance of {@link HiveSerDeManager}.
 *
 * @param props A {@link State} object. To get a specific implementation of {@link HiveSerDeManager}, specify either
 * one of the values in {@link Implementation} (e.g., AVRO or ORC) or the name of a class that implements
 * {@link HiveSerDeManager} in property {@link #HIVE_ROW_FORMAT}. The {@link State} object is also used to
 * instantiate the {@link HiveSerDeManager}.
 */
public static HiveSerDeManager get(State props) {
  String type = props.getProp(HIVE_ROW_FORMAT, Implementation.AVRO.name());
  Optional<Implementation> implementation = Enums.getIfPresent(Implementation.class, type.toUpperCase());

  try {
    if (implementation.isPresent()) {
      return (HiveSerDeManager) ConstructorUtils.invokeConstructor(Class.forName(implementation.get().toString()),
          props);
    }
    return (HiveSerDeManager) ConstructorUtils.invokeConstructor(Class.forName(type), props);
  } catch (ReflectiveOperationException e) {
    throw new RuntimeException(
        "Unable to instantiate " + HiveSerDeManager.class.getSimpleName() + " with type " + type, e);
  }
}
 
Example 18
Source Project: incubator-gobblin   Source File: TopologySpec.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * @return A {@link SpecExecutor}'s instance defined by <Technology, Location, Communication Mechanism>
 */
public synchronized SpecExecutor getSpecExecutor() {
  if (null == specExecutorInstance) {
    String specExecutorClass = DEFAULT_SPEC_EXECUTOR_INSTANCE;
    if (config.hasPath(SPEC_EXECUTOR_INSTANCE_KEY)) {
      specExecutorClass = config.getString(SPEC_EXECUTOR_INSTANCE_KEY);
    }
    try {
      ClassAliasResolver<SpecExecutor> _aliasResolver =
          new ClassAliasResolver<>(SpecExecutor.class);
      specExecutorInstance = (SpecExecutor) ConstructorUtils
          .invokeConstructor(Class.forName(_aliasResolver
              .resolve(specExecutorClass)), config);
    } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException | InstantiationException
        | ClassNotFoundException e) {
      throw new RuntimeException(e);
    }
  }
  return specExecutorInstance;
}
 
Example 19
/**
 * Gets an instance of {@link JobLock}.
 *
 * @param properties the properties used to determine which instance of {@link JobLock} to create and the
 *                   relevant settings
 * @param jobLockEventListener the {@link JobLock} event listener
 * @return an instance of {@link JobLock}
 * @throws JobLockException throw when the {@link JobLock} fails to initialize
 */
public static JobLock getJobLock(Properties properties, JobLockEventListener jobLockEventListener)
        throws JobLockException {
  Preconditions.checkNotNull(properties);
  Preconditions.checkNotNull(jobLockEventListener);
  JobLock jobLock;
  if (properties.containsKey(ConfigurationKeys.JOB_LOCK_TYPE)) {
    try {
      Class<?> jobLockClass = Class.forName(
          properties.getProperty(ConfigurationKeys.JOB_LOCK_TYPE, FileBasedJobLock.class.getName()));
      jobLock = (JobLock) ConstructorUtils.invokeConstructor(jobLockClass, properties);
    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException |
        NoSuchMethodException | InvocationTargetException e) {
      throw new JobLockException(e);
    }
  } else {
    jobLock = new FileBasedJobLock(properties);
  }
  if (jobLock instanceof ListenableJobLock) {
    ((ListenableJobLock)jobLock).setEventListener(jobLockEventListener);
  }
  return jobLock;
}
 
Example 20
public ScheduledJobConfigurationManager(EventBus eventBus, Config config) {
  super(eventBus, config);

  this.jobSpecs = Maps.newHashMap();
  this.refreshIntervalInSeconds = ConfigUtils.getLong(config, GobblinClusterConfigurationKeys.JOB_SPEC_REFRESH_INTERVAL,
      DEFAULT_JOB_SPEC_REFRESH_INTERVAL);

  this.fetchJobSpecExecutor = Executors.newSingleThreadScheduledExecutor(
      ExecutorsUtils.newThreadFactory(Optional.of(LOGGER), Optional.of("FetchJobSpecExecutor")));

  this.aliasResolver = new ClassAliasResolver<>(SpecConsumer.class);
  try {
    String specConsumerClassName = GobblinClusterConfigurationKeys.DEFAULT_SPEC_CONSUMER_CLASS;
    if (config.hasPath(GobblinClusterConfigurationKeys.SPEC_CONSUMER_CLASS_KEY)) {
      specConsumerClassName = config.getString(GobblinClusterConfigurationKeys.SPEC_CONSUMER_CLASS_KEY);
    }
    LOGGER.info("Using SpecConsumer ClassNameclass name/alias " + specConsumerClassName);
    this._specConsumer = (SpecConsumer) ConstructorUtils
        .invokeConstructor(Class.forName(this.aliasResolver.resolve(specConsumerClassName)), config);
  } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException | InstantiationException
      | ClassNotFoundException e) {
    throw new RuntimeException(e);
  }
}
 
Example 21
Source Project: yarg   Source File: AbstractObjectToStringConverter.java    License: Apache License 2.0 6 votes vote down vote up
protected Object convertFromStringUnresolved(Class<?> parameterClass, String paramValueStr) {
    try {
        Constructor constructor = ConstructorUtils.getAccessibleConstructor(parameterClass, String.class);
        if (constructor != null) {
            return constructor.newInstance(paramValueStr);
        } else {
            Method valueOf = MethodUtils.getAccessibleMethod(parameterClass, "valueOf", String.class);
            if (valueOf != null) {
                return valueOf.invoke(null, paramValueStr);
            }
        }
    } catch (ReflectiveOperationException e) {
        throw new ReportingException(
                String.format("Could not instantiate object with class [%s] from [%s] string.",
                        parameterClass.getCanonicalName(),
                        paramValueStr));
    }
    return paramValueStr;
}
 
Example 22
Source Project: Spark   Source File: UIComponentRegistry.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Instantiate a given class.
 *
 * @param currentClass
 *            Class to instantiate.
 * @param args
 *            Arguments for the class constructor.
 * @return New instance, what else?
 */
private static <T> T instantiate(Class<? extends T> currentClass, Object... args) {
    T instance = null;

    Log.debug("Args: " + Arrays.toString(args));
    Class<? extends Object>[] classes = new Class<?>[args.length];
    try {
        for (int i = 0; i < args.length; i++) {
            classes[i] = args[i].getClass();
        }
        final Constructor<? extends T> ctor = ConstructorUtils.getMatchingAccessibleConstructor(currentClass, classes);
        instance = ctor.newInstance(args);
    } catch (final Exception e) {
        // not pretty but we're catching several exceptions we can do little
        // about
        Log.error("Error calling constructor for " + currentClass.getName() + " with arguments " + classes, e);
    }
    return instance;
}
 
Example 23
Source Project: vjtools   Source File: ReflectionUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 调用构造函数.
 */
public static <T> T invokeConstructor(final Class<T> cls, Object... args) {
	try {
		return ConstructorUtils.invokeConstructor(cls, args);
	} catch (Exception e) {
		throw ExceptionUtil.unwrapAndUnchecked(e);
	}
}
 
Example 24
Source Project: vjtools   Source File: ReflectionUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 调用构造函数.
 */
public static <T> T invokeConstructor(final Class<T> cls, Object... args) {
	try {
		return ConstructorUtils.invokeConstructor(cls, args);
	} catch (Exception e) {
		throw ExceptionUtil.unwrapAndUnchecked(e);
	}
}
 
Example 25
Source Project: kafka-connect-fs   Source File: ReflectionUtils.java    License: Apache License 2.0 5 votes vote down vote up
private static <T> T make(Class<T> clazz, Object... args) {
    try {
        Class[] constClasses = Arrays.stream(args).map(Object::getClass).toArray(Class[]::new);

        Constructor<T> constructor = ConstructorUtils.getMatchingAccessibleConstructor(clazz, constClasses);
        return constructor.newInstance(args);
    } catch (IllegalAccessException |
            InstantiationException |
            InvocationTargetException e) {
        throw new ConnectException(e.getCause());
    }
}
 
Example 26
Source Project: soundwave   Source File: AwsServiceTagUpdater.java    License: Apache License 2.0 5 votes vote down vote up
private AwsServiceTagUpdater(CloudInstanceStore store) {
  Preconditions.checkNotNull(store);
  this.cloudStore = store;
  String
      tagsGeneratorClass =
      Configuration.getProperties()
          .getString("aws_tag_generator", "BasicUploadTagsGenerator");
  try {
    this.tagsGenerator =
        (UploadTagsGenerator) ConstructorUtils
            .invokeConstructor(Class.forName(tagsGeneratorClass), null);
  } catch (Exception ex) {

  }
}
 
Example 27
Source Project: cyberduck   Source File: Factory.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * @return A new instance of the type of objects this
 * factory creates
 */
protected T create() {
    if(null == clazz) {
        throw new FactoryException(String.format("No implementation given for factory %s", this.getClass().getSimpleName()));
    }
    try {
        return ConstructorUtils.getMatchingAccessibleConstructor(clazz).newInstance();
    }
    catch(InstantiationException | IllegalAccessException | InvocationTargetException e) {
        throw new FactoryException(e.getMessage(), e);
    }
}
 
Example 28
Source Project: cyberduck   Source File: LocalFactory.java    License: GNU General Public License v3.0 5 votes vote down vote up
protected Local create(final Local parent, final String path) {
    try {
        final Constructor<Local> constructor = ConstructorUtils.getMatchingAccessibleConstructor(clazz, parent.getClass(), path.getClass());
        return constructor.newInstance(parent, path);
    }
    catch(InstantiationException | InvocationTargetException | IllegalAccessException e) {
        throw new FactoryException(e.getMessage(), e);
    }
}
 
Example 29
public Deserializer<T> create(final T dict) {
    try {
        final Constructor<Deserializer> constructor = ConstructorUtils.getMatchingAccessibleConstructor(clazz, dict.getClass());
        return constructor.newInstance(dict);
    }
    catch(InstantiationException | IllegalAccessException | InvocationTargetException e) {
        throw new FactoryException(e.getMessage(), e);
    }
}
 
Example 30
public PeriodicUpdateChecker create(final Controller controller) {
    try {
        final Constructor<PeriodicUpdateChecker> constructor = ConstructorUtils.getMatchingAccessibleConstructor(clazz, controller.getClass());
        if(null == constructor) {
            log.warn(String.format("No matching constructor for parameter %s", controller.getClass()));
            // Call default constructor for disabled implementations
            return clazz.newInstance();
        }
        return constructor.newInstance(controller);
    }
    catch(InstantiationException | InvocationTargetException | IllegalAccessException e) {
        log.error(String.format("Failure loading callback class %s. %s", clazz, e.getMessage()));
        return new DisabledPeriodicUpdater();
    }
}