Java 类org.apache.commons.lang3.reflect.ConstructorUtils 实例源码
项目:cyberduck
文件:PeriodicUpdateCheckerFactory.java
public PeriodicUpdateChecker create(final Controller controller) {
final String clazz = PreferencesFactory.get().getProperty("factory.updater.class");
if(null == clazz) {
throw new FactoryException(String.format("No implementation given for factory %s", this.getClass().getSimpleName()));
}
try {
final Class<PeriodicUpdateChecker> name = (Class<PeriodicUpdateChecker>) Class.forName(clazz);
final Constructor<PeriodicUpdateChecker> constructor = ConstructorUtils.getMatchingAccessibleConstructor(name, controller.getClass());
if(null == constructor) {
log.warn(String.format("No matching constructor for parameter %s", controller.getClass()));
// Call default constructor for disabled implementations
return name.newInstance();
}
return constructor.newInstance(controller);
}
catch(InstantiationException | InvocationTargetException | ClassNotFoundException | IllegalAccessException e) {
log.error(String.format("Failure loading callback class %s. %s", clazz, e.getMessage()));
return new DisabledPeriodicUpdater();
}
}
项目:cyberduck
文件:LoginCallbackFactory.java
public LoginCallback create(final Controller controller) {
final String clazz = PreferencesFactory.get().getProperty("factory.logincallback.class");
if(null == clazz) {
throw new FactoryException(String.format("No implementation given for factory %s", this.getClass().getSimpleName()));
}
try {
final Class<LoginCallback> name = (Class<LoginCallback>) Class.forName(clazz);
final Constructor<LoginCallback> constructor = ConstructorUtils.getMatchingAccessibleConstructor(name, controller.getClass());
if(null == constructor) {
log.warn(String.format("No matching constructor for parameter %s", controller.getClass()));
// Call default constructor for disabled implementations
return name.newInstance();
}
return constructor.newInstance(controller);
}
catch(InstantiationException | InvocationTargetException | ClassNotFoundException | IllegalAccessException e) {
log.error(String.format("Failure loading callback class %s. %s", clazz, e.getMessage()));
return new DisabledLoginCallback();
}
}
项目:cyberduck
文件:CertificateStoreFactory.java
public CertificateStore create(final Controller c) {
final String clazz = PreferencesFactory.get().getProperty("factory.certificatestore.class");
if(null == clazz) {
throw new FactoryException(String.format("No implementation given for factory %s", this.getClass().getSimpleName()));
}
try {
final Class<CertificateStore> name = (Class<CertificateStore>) Class.forName(clazz);
final Constructor<CertificateStore> constructor = ConstructorUtils.getMatchingAccessibleConstructor(name, c.getClass());
if(null == constructor) {
log.warn(String.format("No matching constructor for parameter %s", c.getClass()));
// Call default constructor for disabled implementations
return name.newInstance();
}
return constructor.newInstance(c);
}
catch(InstantiationException | InvocationTargetException | ClassNotFoundException | IllegalAccessException e) {
throw new FactoryException(e.getMessage(), e);
}
}
项目:cyberduck
文件:AlertCallbackFactory.java
public AlertCallback create(final Controller controller) {
final String clazz = PreferencesFactory.get().getProperty("factory.alertcallback.class");
if(null == clazz) {
throw new FactoryException(String.format("No implementation given for factory %s", this.getClass().getSimpleName()));
}
try {
final Class<AlertCallback> name = (Class<AlertCallback>) Class.forName(clazz);
final Constructor<AlertCallback> constructor = ConstructorUtils.getMatchingAccessibleConstructor(name, controller.getClass());
if(null == constructor) {
log.warn(String.format("No matching constructor for parameter %s", controller.getClass()));
// Call default constructor for disabled implementations
return name.newInstance();
}
return constructor.newInstance(controller);
}
catch(InstantiationException | InvocationTargetException | ClassNotFoundException | IllegalAccessException e) {
log.error(String.format("Failure loading callback class %s. %s", clazz, e.getMessage()));
return new DisabledAlertCallback();
}
}
项目:cyberduck
文件:HostKeyCallbackFactory.java
public HostKeyCallback create(final Controller c, final Protocol protocol) {
if(Scheme.sftp.equals(protocol.getScheme())) {
final String clazz = PreferencesFactory.get().getProperty("factory.hostkeycallback.class");
if(null == clazz) {
throw new FactoryException(String.format("No implementation given for factory %s", this.getClass().getSimpleName()));
}
try {
final Class<HostKeyCallback> name = (Class<HostKeyCallback>) Class.forName(clazz);
final Constructor<HostKeyCallback> constructor = ConstructorUtils.getMatchingAccessibleConstructor(name, c.getClass());
if(null == constructor) {
log.warn(String.format("No matching constructor for parameter %s", c.getClass()));
// Call default constructor for disabled implementations
return name.newInstance();
}
return constructor.newInstance(c);
}
catch(InstantiationException | InvocationTargetException | ClassNotFoundException | IllegalAccessException e) {
log.error(String.format("Failure loading callback class %s. %s", clazz, e.getMessage()));
return new DisabledHostKeyCallback();
}
}
return new DisabledHostKeyCallback();
}
项目:cyberduck
文件:VaultFactory.java
private Vault create(final Path directory, final PasswordStore keychain) {
final String clazz = PreferencesFactory.get().getProperty("factory.vault.class");
if(null == clazz) {
throw new FactoryException(String.format("No implementation given for factory %s", this.getClass().getSimpleName()));
}
try {
final Class<Vault> name = (Class<Vault>) Class.forName(clazz);
final Constructor<Vault> constructor = ConstructorUtils.getMatchingAccessibleConstructor(name,
directory.getClass(), keychain.getClass());
if(null == constructor) {
log.warn(String.format("No matching constructor for parameter %s", directory.getClass()));
// Call default constructor for disabled implementations
return name.newInstance();
}
return constructor.newInstance(directory, keychain);
}
catch(InstantiationException | InvocationTargetException | ClassNotFoundException | IllegalAccessException e) {
log.error(String.format("Failure loading callback class %s. %s", clazz, e.getMessage()));
return Vault.DISABLED;
}
}
项目:cyberduck
文件:TransferErrorCallbackControllerFactory.java
public TransferErrorCallback create(final Controller c) {
final String clazz = preferences.getProperty("factory.transfererrorcallback.class");
if(null == clazz) {
throw new FactoryException(String.format("No implementation given for factory %s", this.getClass().getSimpleName()));
}
try {
final Class<TransferErrorCallback> name = (Class<TransferErrorCallback>) Class.forName(clazz);
final Constructor<TransferErrorCallback> constructor = ConstructorUtils.getMatchingAccessibleConstructor(name, c.getClass());
if(null == constructor) {
log.warn(String.format("No matching constructor for parameter %s", c.getClass()));
// Call default constructor for disabled implementations
return name.newInstance();
}
return constructor.newInstance(c);
}
catch(InstantiationException | InvocationTargetException | ClassNotFoundException | IllegalAccessException e) {
log.error(String.format("Failure loading callback class %s. %s", clazz, e.getMessage()));
return new DisabledTransferErrorCallback();
}
}
项目:cyberduck
文件:ThreadPoolFactory.java
/**
* @param size Maximum pool size
* @param handler Uncaught thread exception handler
*/
protected ThreadPool create(final String prefix, final Integer size, final Thread.UncaughtExceptionHandler handler) {
final String clazz = PreferencesFactory.get().getProperty("factory.threadpool.class");
if(null == clazz) {
throw new FactoryException(String.format("No implementation given for factory %s", this.getClass().getSimpleName()));
}
try {
final Class<ThreadPool> name = (Class<ThreadPool>) Class.forName(clazz);
final Constructor<ThreadPool> constructor = ConstructorUtils.getMatchingAccessibleConstructor(name,
prefix.getClass(), size.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 name.newInstance();
}
return constructor.newInstance(prefix, size, handler);
}
catch(InstantiationException | InvocationTargetException | ClassNotFoundException | IllegalAccessException e) {
throw new FactoryException(e.getMessage(), e);
}
}
项目:cyberduck
文件:PasswordCallbackFactory.java
public PasswordCallback create(final Controller controller) {
final String clazz = PreferencesFactory.get().getProperty("factory.passwordcallback.class");
if(null == clazz) {
throw new FactoryException(String.format("No implementation given for factory %s", this.getClass().getSimpleName()));
}
try {
final Class<PasswordCallback> name = (Class<PasswordCallback>) Class.forName(clazz);
final Constructor<PasswordCallback> constructor = ConstructorUtils.getMatchingAccessibleConstructor(name, controller.getClass());
if(null == constructor) {
log.warn(String.format("No matching constructor for parameter %s", controller.getClass()));
// Call default constructor for disabled implementations
return name.newInstance();
}
return constructor.newInstance(controller);
}
catch(InstantiationException | InvocationTargetException | ClassNotFoundException | IllegalAccessException e) {
log.error(String.format("Failure loading callback class %s. %s", clazz, e.getMessage()));
return new DisabledPasswordCallback();
}
}
项目:PacketControl
文件:PacketControlService.java
@Override
public <P extends Packet, A> P createPacket(PacketType<P, A> type, A param) {
if(type.getSide() == PacketSide.SERVERBOUND) {
throw new IllegalArgumentException("You can't initialize a serverbound packet");
}
PacketFactory<P, A> factory = ((PacketControlType<P, A>)type).getFactory();
if(factory != null) {
return factory.create(param);
}
try {
return ConstructorUtils.invokeConstructor(type.getPacketClass(), param);
} catch(Exception ex) {
throw new RuntimeException("There was an issue constructing " + type.getName(), ex);
}
}
项目:clouseau
文件:ClouseauConfiguration.java
@NotNull
public ObjectReader getObjectReader() {
if (reader == null) {
if (TomcatStandardSessionObjectReader.class.getName().equals(getObjectReaderClassName())) {
reader = getTomcatStandardSessionObjectReader();
} else {
try {
reader = (ObjectReader) ConstructorUtils.invokeConstructor(
Class.forName(getObjectReaderClassName()));
} catch (ReflectiveOperationException e) {
throw new IllegalArgumentException("Unable to construct ObjectReader class [" +
getObjectReaderClassName() + "]", e);
}
}
}
return reader;
}
项目:clouseau
文件:ClouseauConfiguration.java
@Nullable
public InputStreamTransformer getInputStreamTransformer() {
InputStreamTransformer result;
if (getInputStreamTransformerClassName() == null) {
result = null;
} else {
try {
result = (InputStreamTransformer) ConstructorUtils.invokeConstructor(
Class.forName(getInputStreamTransformerClassName()));
} catch (ReflectiveOperationException e) {
throw new IllegalArgumentException("Could not construct specified transformer [" +
getInputStreamTransformerClassName() + "]", e);
}
}
return result;
}
项目:jsen-core
文件:MimeContentRegistryBase.java
/**
* Constructs MIME content factory from a given class and constructor arguments.
*
* @param factoryClass MIME content factory class of which should be constructed the instance.
* @param args Constructor arguments for factory.
* @return Constructed MIME content factory on success, otherwise null.
*/
protected MimeContentFactory instantizeMimeContentFactory(Class<? extends MimeContentFactory> factoryClass, Object ...args) {
MimeContentFactory mimeContentFactory = null;
try {
/*List<Class<?>> constructorClassesList = new ArrayList<Class<?>>();
for (Object arg : args) {
constructorClassesList.add(arg.getClass());
}
Class<?> constructorClasses[] = constructorClassesList.toArray(new Class<?>[constructorClassesList.size()]);
Constructor<? extends MimeContentFactoryBase<?>> mimeContentFactoryConstructor = factoryClass.getConstructor(constructorClasses);
mimeContentFactory = mimeContentFactoryConstructor.newInstance(args);*/
Object newInstance = ConstructorUtils.invokeConstructor(factoryClass, args);
mimeContentFactory = factoryClass.cast(newInstance);
} catch (Exception e) {
e.printStackTrace();
}
return mimeContentFactory;
}
项目:sdcct
文件:AbstractApplicationInitializerRunListener.java
protected T buildInitializer(Supplier<T> defaultSupplier, Object ... args) {
List<String> initClassNames = SpringFactoriesLoader.loadFactoryNames(initClass, Thread.currentThread().getContextClassLoader());
if (initClassNames.isEmpty()) {
return defaultSupplier.get();
}
List<Class<?>> initClasses = ClassUtils.convertClassNamesToClasses(initClassNames);
initClasses.sort(AnnotationAwareOrderComparator.INSTANCE);
Class<?> primaryInitClass = initClasses.get(0);
try {
return this.initClass.cast(ConstructorUtils.invokeConstructor(primaryInitClass, args));
} catch (IllegalAccessException | InstantiationException | InvocationTargetException | NoSuchMethodException e) {
throw new ApplicationContextException(String.format("Unable to instantiate application initializer (class=%s).", primaryInitClass.getName()), e);
}
}
项目:sdcct
文件:SdcctNamespaceHandler.java
@Override
public void init() {
SdcctBeanDefinitionParser beanDefParser;
for (Class<?> beanDefClass : ClassUtils
.convertClassNamesToClasses(SpringFactoriesLoader.loadFactoryNames(SdcctBeanDefinitionParser.class, this.getClass().getClassLoader()))) {
try {
beanDefParser = ((SdcctBeanDefinitionParser) ConstructorUtils.invokeConstructor(beanDefClass, this));
} catch (IllegalAccessException | InstantiationException | InvocationTargetException | NoSuchMethodException e) {
throw new ApplicationContextException(String.format("Unable to instantiate bean definition parser (class=%s).", beanDefClass.getName()), e);
}
for (String beanDefParserElemLocalName : beanDefParser.getElementBeanClasses().keySet()) {
this.beanDefParsers.put(beanDefParserElemLocalName, beanDefParser);
this.registerBeanDefinitionParser(beanDefParserElemLocalName, beanDefParser);
}
}
}
项目:testclient
文件:GeneratorInstanceFactory.java
@Override
public synchronized Generator<T> getGenerator() {
if (isSharedInstance && theSharedInstance != null) {
return theSharedInstance;
}
generatorClass = (Class<Generator<T>>) getGeneratorClass(generatorSpec);
try {
Generator<T> generator = ConstructorUtils.invokeConstructor(generatorClass, generatorArgs);
if (isSharedInstance) {
theSharedInstance = generator;
return theSharedInstance;
}
return generator;
} catch (Exception e) {
logger.error(e.getMessage());
throw new RuntimeException(e);
}
}
项目:crigtt
文件:AbstractCrigttApplicationRunListener.java
protected static <T> T buildComponent(Class<T> componentClass, Supplier<T> defaultSupplier, Object ... args) {
List<String> componentClassNames = SpringFactoriesLoader.loadFactoryNames(componentClass, AbstractCrigttApplicationRunListener.class.getClassLoader());
if (componentClassNames.isEmpty()) {
return defaultSupplier.get();
}
List<Class<?>> componentClasses = ClassUtils.convertClassNamesToClasses(componentClassNames);
componentClasses.sort(AnnotationAwareOrderComparator.INSTANCE);
Class<?> primaryComponentClass = componentClasses.get(0);
try {
return componentClass.cast(ConstructorUtils.invokeConstructor(primaryComponentClass, args));
} catch (IllegalAccessException | InstantiationException | InvocationTargetException | NoSuchMethodException e) {
throw new ApplicationContextException(String.format("Unable to instantiate component (class=%s).", primaryComponentClass.getName()), e);
}
}
项目:incubator-gobblin
文件:DefaultAuditSinkFactory.java
/**
* 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);
}
}
项目:incubator-gobblin
文件:ReflectionCompactorListenerFactory.java
@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));
}
项目:incubator-gobblin
文件:GobblinConstructorUtils.java
/**
* 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");
}
项目:incubator-gobblin
文件:GobblinConstructorUtils.java
/**
* 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)));
}
项目:incubator-gobblin
文件:KafkaSchemaRegistryFactory.java
@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);
}
}
项目:incubator-gobblin
文件:HiveSerDeManager.java
/**
* Get an instance of {@link HiveSerDeManager}.
*
* @param type The {@link HiveSerDeManager} type. It should be either AVRO, or the name of a class that implements
* {@link HiveSerDeManager}. The specified {@link HiveSerDeManager} type must have a constructor that takes a
* {@link State} object.
* @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 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);
}
}
项目:incubator-gobblin
文件:TopologySpec.java
/**
* @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;
}
项目:incubator-gobblin
文件:ServiceBasedAppLauncher.java
private void addServicesFromProperties(Properties properties)
throws IllegalAccessException, InstantiationException, ClassNotFoundException, InvocationTargetException {
if (properties.containsKey(APP_ADDITIONAL_SERVICES)) {
for (String serviceClassName : new State(properties).getPropAsSet(APP_ADDITIONAL_SERVICES)) {
Class<?> serviceClass = Class.forName(serviceClassName);
if (Service.class.isAssignableFrom(serviceClass)) {
Service service;
Constructor<?> constructor =
ConstructorUtils.getMatchingAccessibleConstructor(serviceClass, Properties.class);
if (constructor != null) {
service = (Service) constructor.newInstance(properties);
} else {
service = (Service) serviceClass.newInstance();
}
addService(service);
} else {
throw new IllegalArgumentException(String.format("Class %s specified by %s does not implement %s",
serviceClassName, APP_ADDITIONAL_SERVICES, Service.class.getSimpleName()));
}
}
}
}
项目:incubator-gobblin
文件:LegacyJobLockFactoryManager.java
/**
* 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;
}
项目:incubator-gobblin
文件:ScheduledJobConfigurationManager.java
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);
}
}
项目:ScriptBox
文件:MimeContentRegistryBase.java
/**
* Constructs MIME content factory from a given class and constructor arguments.
*
* @param factoryClass MIME content factory class of which should be constructed the instance.
* @param args Constructor arguments for factory.
* @return Constructed MIME content factory on success, otherwise null.
*/
protected MimeContentFactory instantizeMimeContentFactory(Class<? extends MimeContentFactory> factoryClass, Object ...args) {
MimeContentFactory mimeContentFactory = null;
try {
/*List<Class<?>> constructorClassesList = new ArrayList<Class<?>>();
for (Object arg : args) {
constructorClassesList.add(arg.getClass());
}
Class<?> constructorClasses[] = constructorClassesList.toArray(new Class<?>[constructorClassesList.size()]);
Constructor<? extends MimeContentFactoryBase<?>> mimeContentFactoryConstructor = factoryClass.getConstructor(constructorClasses);
mimeContentFactory = mimeContentFactoryConstructor.newInstance(args);*/
Object newInstance = ConstructorUtils.invokeConstructor(factoryClass, args);
mimeContentFactory = factoryClass.cast(newInstance);
} catch (Exception e) {
e.printStackTrace();
}
return mimeContentFactory;
}
项目:yarg
文件:AbstractObjectToStringConverter.java
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;
}
项目:soundwave
文件:AwsServiceTagUpdater.java
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) {
}
}
项目:cyberduck
文件:FilesystemFactory.java
public Filesystem create(final Controller controller, final Host bookmark, final Cache<Path> cache) {
final String clazz = PreferencesFactory.get().getProperty("factory.filesystem.class");
if(null == clazz) {
throw new FactoryException(String.format("No implementation given for factory %s", this.getClass().getSimpleName()));
}
try {
final Class<Filesystem> name = (Class<Filesystem>) Class.forName(clazz);
final Constructor<Filesystem> constructor = ConstructorUtils.getMatchingAccessibleConstructor(name,
controller.getClass(), bookmark.getClass(), cache.getClass());
return constructor.newInstance(controller, bookmark, cache);
}
catch(InstantiationException | InvocationTargetException | ClassNotFoundException | IllegalAccessException e) {
throw new FactoryException(e.getMessage(), e);
}
}
项目:cyberduck
文件:LocalFactory.java
protected Local create(final String path) {
final String clazz = PreferencesFactory.get().getProperty("factory.local.class");
if(null == clazz) {
throw new FactoryException(String.format("No implementation given for factory %s", this.getClass().getSimpleName()));
}
try {
final Class<Local> name = (Class<Local>) Class.forName(clazz);
final Constructor<Local> constructor = ConstructorUtils.getMatchingAccessibleConstructor(name, path.getClass());
return constructor.newInstance(path);
}
catch(InstantiationException | InvocationTargetException | ClassNotFoundException | IllegalAccessException e) {
throw new FactoryException(e.getMessage(), e);
}
}
项目:cyberduck
文件:LocalFactory.java
protected Local create(final Local parent, final String path) {
final String clazz = PreferencesFactory.get().getProperty("factory.local.class");
if(null == clazz) {
throw new FactoryException(String.format("No implementation given for factory %s", this.getClass().getSimpleName()));
}
try {
final Class<Local> name = (Class<Local>) Class.forName(clazz);
final Constructor<Local> constructor = ConstructorUtils.getMatchingAccessibleConstructor(name, parent.getClass(), path.getClass());
return constructor.newInstance(parent, path);
}
catch(InstantiationException | InvocationTargetException | ClassNotFoundException | IllegalAccessException e) {
throw new FactoryException(e.getMessage(), e);
}
}
项目:cyberduck
文件:DeserializerFactory.java
public Deserializer create(final T dict) {
if(null == clazz) {
throw new FactoryException(String.format("No implementation given for factory %s", this.getClass().getSimpleName()));
}
try {
final Class<Deserializer> name = (Class<Deserializer>) Class.forName(clazz);
final Constructor<Deserializer> constructor = ConstructorUtils.getMatchingAccessibleConstructor(name, dict.getClass());
return constructor.newInstance(dict);
}
catch(InstantiationException | IllegalAccessException | InvocationTargetException | ClassNotFoundException e) {
throw new FactoryException(e.getMessage(), e);
}
}
项目:cyberduck
文件:SessionFactory.java
public static Session<?> create(final Host host, final X509TrustManager trust, final X509KeyManager key) {
if(log.isDebugEnabled()) {
log.debug(String.format("Create session for %s", host));
}
final Protocol protocol = host.getProtocol();
final String prefix = protocol.getPrefix();
try {
final Class<Session> name = (Class<Session>) Class.forName(String.format("%sSession", prefix));
final Constructor<Session> constructor = ConstructorUtils.getMatchingAccessibleConstructor(name,
host.getClass(), trust.getClass(), key.getClass());
final Session<?> session;
if(null == constructor) {
log.warn(String.format("No matching constructor for parameter %s, %s, %s", host.getClass(), trust.getClass(), key.getClass()));
final Constructor<Session> fallback = ConstructorUtils.getMatchingAccessibleConstructor(name,
host.getClass());
if(fallback == null) {
throw new FactoryException(String.format("No matching constructor for parameter %s", host.getClass()));
}
session = fallback.newInstance(host);
}
else {
session = constructor.newInstance(host, trust, key);
}
return session;
}
catch(InstantiationException | InvocationTargetException | ClassNotFoundException | IllegalAccessException e) {
throw new FactoryException(String.format("Failure loading session class for %s protocol. Failure %s", protocol, e));
}
}
项目:UniversalRemote
文件:RemoteGuiMessage.java
public static FMLMessage.OpenGui create (int windowId, String modId, int modGuiId, int x, int y, int z)
{
try {
return ConstructorUtils.invokeConstructor(FMLMessage.OpenGui.class, windowId, modId, modGuiId, x, y, z);
} catch (Exception e) {
Util.logger.logException("Unable to construct FMLMessage.OpenGui using factory!", e);
return null;
}
}
项目:PacketControl
文件:PacketControlService.java
@Override
public <P extends Packet> P createPacket(PacketType<P, ?> type) {
if(type.getSide() == PacketSide.SERVERBOUND) {
throw new IllegalArgumentException("You can't initialize a serverbound packet");
}
try {
return ConstructorUtils.invokeConstructor(type.getPacketClass());
} catch(Exception ex) {
throw new RuntimeException("There was an issue constructing " + type.getName(), ex);
}
}
项目:util
文件:ReflectionUtil.java
/**
* 调用构造函数.
*/
public static <T> T invokeConstructor(final Class<T> cls, Object... args) {
try {
return ConstructorUtils.invokeConstructor(cls, args);
} catch (Exception e) {
throw ExceptionUtil.uncheckedAndWrap(e);
}
}
项目:carbon
文件:NoArgsConstructorUtil.java
public static <T> T construct(Class<T> type) throws ConstructionException {
try {
return ConstructorUtils.invokeExactConstructor(type);
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException | InstantiationException e) {
throw new ConstructionException(type, e);
}
}
项目:carbon
文件:NoArgsConstructorUtil.java
public static <T> T construct(Class<T> type, Object enclosing) throws ConstructionException {
assertInnerNoStaticArguments(type, enclosing);
try {
return ConstructorUtils.invokeExactConstructor(type, enclosing);
} catch (NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) {
throw new ConstructionException(type, e);
}
}