Java Code Examples for java.lang.reflect.Constructor

The following examples show how to use java.lang.reflect.Constructor. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: spring-boot-email-tools   Source File: TimeUtilsTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void shouldBeUtilityClass() throws Exception {
    //Arrange
    Constructor<?> constructor = TimeUtils.class.getDeclaredConstructor();
    assertions.assertThat(Modifier.isPrivate(constructor.getModifiers()))
            .as("Constructor of an Utility Class should be private")
            .isTrue();
    constructor.setAccessible(true);

    expectedException.expectCause(
            allOf(instanceOf(UnsupportedOperationException.class),
                    hasProperty("message", equalTo("This is a utility class and cannot be instantiated"))
            ));

    //Act
    constructor.newInstance();
}
 
Example 2
Source Project: Tomcat8-Source-Read   Source File: WebappLoader.java    License: MIT License 6 votes vote down vote up
/**
 * Create associated classLoader.
 */
private WebappClassLoaderBase createClassLoader()
    throws Exception {

    Class<?> clazz = Class.forName(loaderClass);
    WebappClassLoaderBase classLoader = null;

    if (parentClassLoader == null) {
        parentClassLoader = context.getParentClassLoader();
    }
    Class<?>[] argTypes = { ClassLoader.class };
    Object[] args = { parentClassLoader };
    Constructor<?> constr = clazz.getConstructor(argTypes);
    classLoader = (WebappClassLoaderBase) constr.newInstance(args);

    return classLoader;
}
 
Example 3
Source Project: businessworks   Source File: BytecodeGen.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns true if the member can be called by a fast class generated in a different classloader.
 */
private static boolean isPubliclyCallable(Member member) {
  if (!Modifier.isPublic(member.getModifiers())) {
    return false;
  }
  Class<?>[] parameterTypes;
  if (member instanceof Constructor) {
    parameterTypes = ((Constructor) member).getParameterTypes();
  } else {
    Method method = (Method) member;
    if (!Modifier.isPublic(method.getReturnType().getModifiers())) {
      return false;
    }
    parameterTypes = method.getParameterTypes();
  }

  for (Class<?> type : parameterTypes) {
    if (!Modifier.isPublic(type.getModifiers())) {
      return false;
    }
  }
  return true;
}
 
Example 4
/**
    * Constructs a ModelMBeanConstructorInfo object with a default
    * descriptor.  The {@link Descriptor} of the constructed
    * object will include fields contributed by any annotations on
    * the {@code Constructor} object that contain the {@link
    * DescriptorKey} meta-annotation.
    *
    * @param description A human readable description of the constructor.
    * @param constructorMethod The java.lang.reflect.Constructor object
    * describing the MBean constructor.
    */
    public ModelMBeanConstructorInfo(String description,
                                     Constructor<?> constructorMethod)
{
            super(description, constructorMethod);
            if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) {
                MODELMBEAN_LOGGER.logp(Level.FINER,
                        ModelMBeanConstructorInfo.class.getName(),
                        "ModelMBeanConstructorInfo(String,Constructor)",
                        "Entry");
            }
            consDescriptor = validDescriptor(null);

            // put getter and setter methods in constructors list
            // create default descriptor

    }
 
Example 5
Source Project: Bytecoder   Source File: CRLExtensions.java    License: Apache License 2.0 6 votes vote down vote up
private void parseExtension(Extension ext) throws CRLException {
    try {
        Class<?> extClass = OIDMap.getClass(ext.getExtensionId());
        if (extClass == null) {   // Unsupported extension
            if (ext.isCritical())
                unsupportedCritExt = true;
            if (map.put(ext.getExtensionId().toString(), ext) != null)
                throw new CRLException("Duplicate extensions not allowed");
            return;
        }
        Constructor<?> cons = extClass.getConstructor(PARAMS);
        Object[] passed = new Object[] {Boolean.valueOf(ext.isCritical()),
                                        ext.getExtensionValue()};
        CertAttrSet<?> crlExt = (CertAttrSet<?>)cons.newInstance(passed);
        if (map.put(crlExt.getName(), (Extension)crlExt) != null) {
            throw new CRLException("Duplicate extensions not allowed");
        }
    } catch (InvocationTargetException invk) {
        throw new CRLException(invk.getTargetException().getMessage());
    } catch (Exception e) {
        throw new CRLException(e.toString());
    }
}
 
Example 6
Source Project: openhab1-addons   Source File: OBISMessage.java    License: Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Creates an empty CosemValue object
 *
 * @param cosemValueDescriptor
 *            the CosemValueDescriptor object that describes the CosemValue
 * @return the instantiated CosemValue based on the specified
 *         CosemValueDescriptor
 */
private CosemValue<? extends State> getCosemValue(CosemValueDescriptor cosemValueDescriptor) {
    Class<? extends CosemValue<? extends State>> cosemValueClass = cosemValueDescriptor.getCosemValueClass();

    String unit = cosemValueDescriptor.getUnit();
    String dsmrItemId = cosemValueDescriptor.getDsmrItemId();

    try {
        Constructor<? extends CosemValue<? extends State>> c = cosemValueClass.getConstructor(String.class,
                String.class);

        return c.newInstance(unit, dsmrItemId);
    } catch (ReflectiveOperationException roe) {
        logger.error("Failed to create {} message", msgType.obisId, roe);
    }
    return null;
}
 
Example 7
Source Project: spring4-understanding   Source File: BootstrapUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Create the {@code BootstrapContext} for the specified {@linkplain Class test class}.
 *
 * <p>Uses reflection to create a {@link org.springframework.test.context.support.DefaultBootstrapContext}
 * that uses a {@link org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate}.
 *
 * @param testClass the test class for which the bootstrap context should be created
 * @return a new {@code BootstrapContext}; never {@code null}
 */
@SuppressWarnings("unchecked")
static BootstrapContext createBootstrapContext(Class<?> testClass) {
	CacheAwareContextLoaderDelegate cacheAwareContextLoaderDelegate = createCacheAwareContextLoaderDelegate();

	Class<? extends BootstrapContext> clazz = null;
	try {
		clazz = (Class<? extends BootstrapContext>) ClassUtils.forName(DEFAULT_BOOTSTRAP_CONTEXT_CLASS_NAME,
			BootstrapUtils.class.getClassLoader());

		Constructor<? extends BootstrapContext> constructor = clazz.getConstructor(Class.class,
			CacheAwareContextLoaderDelegate.class);

		if (logger.isDebugEnabled()) {
			logger.debug(String.format("Instantiating BootstrapContext using constructor [%s]", constructor));
		}
		return instantiateClass(constructor, testClass, cacheAwareContextLoaderDelegate);
	}
	catch (Throwable t) {
		throw new IllegalStateException("Could not load BootstrapContext [" + clazz + "]", t);
	}
}
 
Example 8
Source Project: Paginize   Source File: AnnotationUtils.java    License: MIT License 6 votes vote down vote up
public static void handleAnnotatedConstructors(Class clazz,
                                               Object object,
                                               ViewFinder viewFinder,
                                               boolean initForLazy) throws
    InvocationTargetException , IllegalAccessException,
    NoSuchMethodException, InstantiationException {

  Constructor[] constructors = clazz.getDeclaredConstructors();
  for (int i = 0; i < constructors.length; ++i) {
    Constructor constructor = constructors[i];
    Annotation[] annotations = constructor.getAnnotations();
    for (int j = 0; j < annotations.length; ++j) {

      Annotation anno = annotations[j];
      if (anno instanceof ListenerDefs) {
        handleListenerDefs(clazz, object, viewFinder, initForLazy, (ListenerDefs) anno);

      } else if (anno instanceof ListenerDefs2) {
        handleListenerDefs2(clazz, object, viewFinder, initForLazy, (ListenerDefs2) anno);
      }

    }
  }
}
 
Example 9
Source Project: spring-analysis-note   Source File: ConstructorReference.java    License: MIT License 6 votes vote down vote up
@Override
public boolean isCompilable() {
	if (!(this.cachedExecutor instanceof ReflectiveConstructorExecutor) ||
		this.exitTypeDescriptor == null) {
		return false;
	}

	if (getChildCount() > 1) {
		for (int c = 1, max = getChildCount();c < max; c++) {
			if (!this.children[c].isCompilable()) {
				return false;
			}
		}
	}

	ReflectiveConstructorExecutor executor = (ReflectiveConstructorExecutor) this.cachedExecutor;
	if (executor == null) {
		return false;
	}
	Constructor<?> constructor = executor.getConstructor();
	return (Modifier.isPublic(constructor.getModifiers()) &&
			Modifier.isPublic(constructor.getDeclaringClass().getModifiers()));
}
 
Example 10
Source Project: Tomcat7.0.67   Source File: WebappLoader.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Create associated classLoader.
 */
private WebappClassLoaderBase createClassLoader()
    throws Exception {

    Class<?> clazz = Class.forName(loaderClass);
    WebappClassLoaderBase classLoader = null;

    if (parentClassLoader == null) {
        parentClassLoader = container.getParentClassLoader();
    }
    Class<?>[] argTypes = { ClassLoader.class };
    Object[] args = { parentClassLoader };
    Constructor<?> constr = clazz.getConstructor(argTypes);
    classLoader = (WebappClassLoaderBase) constr.newInstance(args);

    return classLoader;

}
 
Example 11
Source Project: cuba   Source File: ConfigDefaultMethod.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Object invoke(ConfigHandler handler, Object[] args, Object proxy) {
    try {
        if (SystemUtils.IS_JAVA_1_8) {
            // hack to invoke default method of an interface reflectively
            Constructor<MethodHandles.Lookup> lookupConstructor =
                    MethodHandles.Lookup.class.getDeclaredConstructor(Class.class, Integer.TYPE);
            if (!lookupConstructor.isAccessible()) {
                lookupConstructor.setAccessible(true);
            }
            return lookupConstructor.newInstance(configInterface, MethodHandles.Lookup.PRIVATE)
                    .unreflectSpecial(configMethod, configInterface)
                    .bindTo(proxy)
                    .invokeWithArguments(args);
        } else {
            return MethodHandles.lookup()
                .findSpecial(configInterface, configMethod.getName(), MethodType.methodType(configMethod.getReturnType(),
                        configMethod.getParameterTypes()), configInterface)
                .bindTo(proxy)
                .invokeWithArguments(args);
        }
    } catch (Throwable throwable) {
        throw new RuntimeException("Error invoking default method of config interface", throwable);
    }
}
 
Example 12
Source Project: jdk8u60   Source File: Connection.java    License: GNU General Public License v2.0 6 votes vote down vote up
private Object createInetSocketAddress(String host, int port)
        throws NoSuchMethodException {

    try {
        Class<?> inetSocketAddressClass =
            Class.forName("java.net.InetSocketAddress");

        Constructor<?> inetSocketAddressCons =
            inetSocketAddressClass.getConstructor(new Class<?>[]{
            String.class, int.class});

        return inetSocketAddressCons.newInstance(new Object[]{
            host, new Integer(port)});

    } catch (ClassNotFoundException |
             InstantiationException |
             InvocationTargetException |
             IllegalAccessException e) {
        throw new NoSuchMethodException();

    }
}
 
Example 13
Source Project: cuba   Source File: AbstractDataGridLoader.java    License: Apache License 2.0 6 votes vote down vote up
protected void loadStrategyClass(AggregationInfo aggregation, Element aggregationElement) {
    String strategyClass = aggregationElement.attributeValue("strategyClass");
    if (StringUtils.isNotEmpty(strategyClass)) {
        Class<?> aggregationClass = getScripting().loadClass(strategyClass);
        if (aggregationClass == null) {
            throw new GuiDevelopmentException(String.format("Class %s is not found", strategyClass), context);
        }

        try {
            Constructor<?> constructor = aggregationClass.getDeclaredConstructor();
            AggregationStrategy customStrategy = (AggregationStrategy) constructor.newInstance();
            aggregation.setStrategy(customStrategy);
        } catch (Exception e) {
            throw new RuntimeException("Unable to instantiate strategy for aggregation", e);
        }
    }
}
 
Example 14
Source Project: crate   Source File: AssistedConstructor.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
AssistedConstructor(Constructor<T> constructor, List<TypeLiteral<?>> parameterTypes) {
    this.constructor = constructor;

    Annotation[][] annotations = constructor.getParameterAnnotations();

    List<Type> typeList = new ArrayList<>();
    allParameters = new ArrayList<>(parameterTypes.size());

    // categorize params as @Assisted or @Injected
    for (int i = 0; i < parameterTypes.size(); i++) {
        Parameter parameter = new Parameter(parameterTypes.get(i).getType(), annotations[i]);
        allParameters.add(parameter);
        if (parameter.isProvidedByFactory()) {
            typeList.add(parameter.getType());
        }
    }
    this.assistedParameters = new ParameterListKey(typeList);
}
 
Example 15
private boolean isMatch(Constructor<?> constructor, Object... params) {
    if (constructor.getParameterTypes().length != params.length) {
        return false;
    }
    for (int i = 0; i < params.length; i++) {
        Object param = params[i];
        Class<?> parameterType = constructor.getParameterTypes()[i];
        if (parameterType.isPrimitive()) {
            if (!JavaReflectionUtil.getWrapperTypeForPrimitiveType(parameterType).isInstance(param)) {
                return false;
            }
        } else {
            if (param != null && !parameterType.isInstance(param)) {
                return false;
            }
        }
    }
    return true;
}
 
Example 16
Source Project: Selenium-Foundation   Source File: GridUtilityTest.java    License: Apache License 2.0 6 votes vote down vote up
@NoDriver
@Test(expectedExceptions = {AssertionError.class},
        expectedExceptionsMessageRegExp = "GridUtility is a static utility class that cannot be instantiated")
public void testPrivateConstructor() throws Throwable {
    
    Constructor<?>[] ctors;
    ctors = GridUtility.class.getDeclaredConstructors();
    assertEquals(ctors.length, 1, "GridUtility must have exactly one constructor");
    assertEquals(ctors[0].getModifiers() & Modifier.PRIVATE, Modifier.PRIVATE,
                    "GridUtility constructor must be private");
    assertEquals(ctors[0].getParameterTypes().length, 0, "GridUtility constructor must have no arguments");
    
    try {
        ctors[0].setAccessible(true);
        ctors[0].newInstance();
    } catch (InvocationTargetException e) {
        throw e.getCause();
    }
}
 
Example 17
Source Project: hottub   Source File: ProxyArrays.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Generate proxy arrays.
 */
Proxy[][] genArrays(int size, int narrays) throws Exception {
    Class proxyClass =
        Proxy.getProxyClass(DummyInterface.class.getClassLoader(),
                new Class[] { DummyInterface.class });
    Constructor proxyCons =
        proxyClass.getConstructor(new Class[] { InvocationHandler.class });
    Object[] consArgs = new Object[] { new DummyHandler() };
    Proxy[][] arrays = new Proxy[narrays][size];
    for (int i = 0; i < narrays; i++) {
        for (int j = 0; j < size; j++) {
            arrays[i][j] = (Proxy) proxyCons.newInstance(consArgs);
        }
    }
    return arrays;
}
 
Example 18
Source Project: jackrabbit-filevault   Source File: RepositoryProvider.java    License: Apache License 2.0 6 votes vote down vote up
private Repository wrapLogger(Repository base,RepositoryAddress address) {
    try {
        Class clazz = getClass().getClassLoader().loadClass("org.apache.jackrabbit.jcrlog.RepositoryLogger");
        // just map all properties
        Properties props = new Properties();
        for (Object o: System.getProperties().keySet()) {
            String name = o.toString();
            if (name.startsWith("jcrlog.")) {
                props.put(name.substring("jcrlog.".length()), System.getProperty(name));
            }
        }
        Constructor c = clazz.getConstructor(Repository.class, Properties.class, String.class);
        return (Repository) c.newInstance(base, props, address.toString());
    } catch (Exception e) {
        log.error("Unable to initialize JCR logger: {}", e.toString());
        return null;
    }
}
 
Example 19
Source Project: database   Source File: BigdataSailFactory.java    License: GNU General Public License v2.0 6 votes vote down vote up
protected static Sail getSailProviderInstance(Properties props) {
   
	final String providerClass = System.getProperty(SAIL_PROVIDER,
			BIGDATA_SAIL_INSTANCE);

	try {
		final Class<?> c = Class.forName(providerClass);
		final Constructor<?> cons = c.getConstructor(Properties.class);
		final Object object = cons.newInstance(props);
		final Sail proxy = (Sail) object;
		return proxy;
	} catch (ClassNotFoundException | NoSuchMethodException
			| SecurityException | InstantiationException
			| IllegalAccessException | IllegalArgumentException
			| InvocationTargetException e) {

		throw new RuntimeException(e);
	}
		
}
 
Example 20
Source Project: DBus   Source File: MetaFetcherManager.java    License: Apache License 2.0 6 votes vote down vote up
private static boolean initializeOraMetaFetcher(String jdbcUrl, String user, String pwd) {
    try {
        Properties properties = PropertiesHolder.getProperties(ORA_DATASOURCE_CONFIG_NAME);
        properties.setProperty("url", jdbcUrl);
        properties.setProperty("username", user);
        properties.setProperty("password", pwd);
        DataSourceProvider provider = new DruidDataSourceProvider(properties);
        Class<?> clazz = Class.forName("com.creditease.dbus.stream.oracle.appender.meta.OraMetaFetcher");
        Constructor<?> constructor = clazz.getConstructor(DataSource.class);
        fetcher = (MetaFetcher) constructor.newInstance(provider.provideDataSource());
        return true;
    } catch (Exception e) {
        logger.error("MetaFetcherManager initializeOraMetaFetcher error!", e);
        return false;
    }
}
 
Example 21
Source Project: ucar-weex-core   Source File: SimpleComponentHolder.java    License: Apache License 2.0 6 votes vote down vote up
private void loadConstructor(){
  Class<? extends WXComponent> c = mCompClz;
  Constructor<? extends WXComponent> constructor;
  try {
    constructor = c.getConstructor(WXSDKInstance.class, WXDomObject.class, WXVContainer.class);
  } catch (NoSuchMethodException e) {
    WXLogUtils.d("ClazzComponentCreator","Use deprecated component constructor");
    try {
      //compatible deprecated constructor with 4 args
      constructor = c.getConstructor(WXSDKInstance.class, WXDomObject.class, WXVContainer.class, boolean.class);
    } catch (NoSuchMethodException e1) {
      try {
        //compatible deprecated constructor with 5 args
        constructor = c.getConstructor(WXSDKInstance.class, WXDomObject.class, WXVContainer.class,String.class, boolean.class);
      } catch (NoSuchMethodException e2) {
        throw new WXRuntimeException("Can't find constructor of component.");
      }
    }
  }
  mConstructor = constructor;
}
 
Example 22
Source Project: Bytecoder   Source File: Util.java    License: Apache License 2.0 6 votes vote down vote up
private static void initDBBRConstructor() {
    AccessController.doPrivileged(new PrivilegedAction<Void>() {
            public Void run() {
                try {
                    Class<?> cl = Class.forName("java.nio.DirectByteBufferR");
                    Constructor<?> ctor = cl.getDeclaredConstructor(
                        new Class<?>[] { int.class,
                                         long.class,
                                         FileDescriptor.class,
                                         Runnable.class,
                                         boolean.class, MemorySegmentProxy.class });
                    ctor.setAccessible(true);
                    directByteBufferRConstructor = ctor;
                } catch (ClassNotFoundException |
                         NoSuchMethodException |
                         IllegalArgumentException |
                         ClassCastException x) {
                    throw new InternalError(x);
                }
                return null;
            }});
}
 
Example 23
Source Project: emissary   Source File: ConstructorLookupCache.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Look for a constructor in the cache.
 *
 * @param clazz The class to be constructed.
 * @param argTypes The argument types that the caller intends to pass to the constructor.
 * @return If a matching constructor is in the cache, return it. Otherwise {@code null}.
 */
public static Constructor<?> get(final Class<?> clazz, final Class<?>[] argTypes) {
    // Currently there is at most one cached lookup per thread, so
    // we can just check if the current thread knows about the
    // given class and constructor arguments.
    final SoftReference<KnownConstructor> softResult = cachedConstructorLookup.get();
    if (softResult == null) {
        return null; // Nothing is currently cached in this thread.
    }

    final KnownConstructor knownResult = softResult.get();
    if (knownResult == null) {
        return null; // There was something cached but it's been lost.
    }

    // We do have a cached lookup. It can be used iff it matches the
    // given class and constructor arguments.
    return knownResult.getConstructor(clazz, argTypes);
}
 
Example 24
Source Project: das   Source File: ORMUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static <T> T map(ResultSet rs, Class<T> clazz) throws Exception {
    Constructor<T> constructor = clazz.getConstructor();
    T instance = constructor.newInstance();
    Field[] fields = clazz.getDeclaredFields();
    Field field = null;
    Method setMethod = null;
    for (int i = 0; i < fields.length; i++) {
        field = fields[i];
        setMethod = clazz.getMethod("set" + StringUtils.capitalize(field.getName()), field.getType());

        if (setMethod == null) {
            field.setAccessible(true);
            field.set(instance, load(field.getType(), rs.getObject(field.getName())));
        } else {
            try {
                setMethod.invoke(instance, load(field.getType(), rs.getObject(field.getName())));
            } catch (Exception ex) {
                System.out.println(ex.getMessage());
                System.out.println("Name: " + field.getName());
            }
        }

    }
    return instance;
}
 
Example 25
/**
 * Get a writer implementation to push data into Canvas while being able to control the behavior of blank values.
 * If the serializeNulls parameter is set to true, this writer will serialize null fields in the JSON being
 * sent to Canvas. This is required if you want to explicitly blank out a value that is currently set to something.
 * @param type Interface type you wish to get an implementation for
 * @param oauthToken An OAuth token to use for authentication when making API calls
 * @param serializeNulls Whether or not to include null fields in the serialized JSON. Defaults to false if null
 * @param <T> A writer implementation
 * @return An instantiated instance of the requested writer type
 */
public <T extends CanvasWriter> T getWriter(Class<T> type, OauthToken oauthToken, Boolean serializeNulls) {
    LOG.debug("Factory call to instantiate class: " + type.getName());
    RestClient restClient = new RefreshingRestClient();

    @SuppressWarnings("unchecked")
    Class<T> concreteClass = (Class<T>) writerMap.get(type);

    if (concreteClass == null) {
        throw new UnsupportedOperationException("No implementation for requested interface found: " + type.getName());
    }

    LOG.debug("got writer class: " + concreteClass);
    try {
        Constructor<T> constructor = concreteClass.getConstructor(String.class, Integer.class, OauthToken.class,
                RestClient.class, Integer.TYPE, Integer.TYPE, Integer.class, Boolean.class);
        return constructor.newInstance(canvasBaseUrl, CANVAS_API_VERSION, oauthToken, restClient,
                connectTimeout, readTimeout, null, serializeNulls);
    } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException | InstantiationException e) {
        throw new UnsupportedOperationException("Unknown error instantiating the concrete API class: " + type.getName(), e);
    }
}
 
Example 26
Source Project: jvm-sandbox-repeater   Source File: Java8TimeSerializer.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void writeObject(Object obj, AbstractHessianOutput out)
        throws IOException {
    if (obj == null) {
        out.writeNull();
        return;
    }
    T handle;
    try {
        Constructor<T> constructor = this.handleType.getConstructor(Object.class);
        handle = constructor.newInstance(obj);
    } catch (Exception e) {
        throw new RuntimeException("the class :" + this.handleType.getName() + " construct failed:" + e.getMessage(), e);
    }
    out.writeObject(handle);
}
 
Example 27
Source Project: openjdk-jdk9   Source File: Main.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Get the correct type of BatchEnvironment
 */
public BatchEnvironment getEnv() {

    ClassPath classPath =
        BatchEnvironment.createClassPath(classPathString,
                                         sysClassPathArg);
    BatchEnvironment result = null;
    try {
        Class<?>[] ctorArgTypes = {OutputStream.class,ClassPath.class,Main.class};
        Object[] ctorArgs = {out,classPath,this};
        Constructor<? extends BatchEnvironment> constructor =
            environmentClass.getConstructor(ctorArgTypes);
        result =  constructor.newInstance(ctorArgs);
        result.reset();
    }
    catch (Exception e) {
        error("rmic.cannot.instantiate",environmentClass.getName());
    }
    return result;
}
 
Example 28
Source Project: ats-framework   Source File: MobileDriver.java    License: Apache License 2.0 6 votes vote down vote up
/**
 *
 * @param command the command to run
 * @param commandArguments command arguments
 * @return {@link IProcessExecutor} implementation instance
 */
private IProcessExecutor getProcessExecutorImpl( String command, String[] commandArguments ) {

    if (isWorkingRemotely) {
        String remoteProcessExecutorClassName = "com.axway.ats.action.processes.RemoteProcessExecutor";
        try {
            Class<?> remotePEClass = Class.forName(remoteProcessExecutorClassName);
            Constructor<?> constructor = remotePEClass.getDeclaredConstructors()[0];
            return (IProcessExecutor) constructor.newInstance(host, command, commandArguments);
        } catch (Exception e) {
            throw new RuntimeException("Unable to instantiate RemoteProcessExecutor. Check whether ATS Action "
                                       + "library and ATS Agent client are added as dependencies in classpath. "
                                       + "They are needed in order to invoke code on remote machine.",
                                       e);
        }
    }
    return new LocalProcessExecutor(HostUtils.LOCAL_HOST_NAME, command, commandArguments);
}
 
Example 29
@SuppressWarnings("unchecked")
public static <T> T invokeConstructor(Class<?> targetClass, Object... args) {
    Assert.notNull(targetClass, "Target class must not be null");

    try {
        for (Constructor<?> constructor : targetClass.getDeclaredConstructors()) {
            if (constructor.getParameterCount() != args.length) {
                continue;
            }
            Class<?>[] parameterTypes = constructor.getParameterTypes();
            boolean parametersMatches = IntStream.range(0, args.length)
                    .allMatch(i -> ClassUtils.isAssignableValue(parameterTypes[i], args[i]));
            if (parametersMatches) {
                org.springframework.util.ReflectionUtils.makeAccessible(constructor);
                return (T) constructor.newInstance(args);
            }
        }
        throw new IllegalArgumentException(String.format("Could not find constructor on %s", targetClass));
    } catch (Exception ex) {
        org.springframework.util.ReflectionUtils.handleReflectionException(ex);
        throw new IllegalStateException("Should never get here");
    }
}
 
Example 30
Source Project: netbeans   Source File: TreeUtilities.java    License: Apache License 2.0 5 votes vote down vote up
private static Scope attributeTreeTo(JavacTaskImpl jti, Tree tree, Scope scope, Tree to, final List<Diagnostic<? extends JavaFileObject>> errors) {
        Log log = Log.instance(jti.getContext());
        JavaFileObject prev = log.useSource(new DummyJFO());
        Log.DiagnosticHandler discardHandler = new Log.DiscardDiagnosticHandler(log) {
            @Override
            public void report(JCDiagnostic diag) {
                errors.add(diag);
            }            
        };
        NBResolve resolve = NBResolve.instance(jti.getContext());
        resolve.disableAccessibilityChecks();
//        Enter enter = Enter.instance(jti.getContext());
//        enter.shadowTypeEnvs(true);
//        ArgumentAttr argumentAttr = ArgumentAttr.instance(jti.getContext());
//        ArgumentAttr.LocalCacheContext cacheContext = argumentAttr.withLocalCacheContext();
        try {
            NBAttr attr = (NBAttr) NBAttr.instance(jti.getContext());
            Env<AttrContext> env = getEnv(scope);
            Env<AttrContext> result = attr.attributeAndCapture((JCTree) tree, env, (JCTree) to);
            try {
                Constructor<JavacScope> c = JavacScope.class.getDeclaredConstructor(Env.class);
                c.setAccessible(true);
                return c.newInstance(result);
            } catch (NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
                throw new IllegalStateException(ex);
            }
        } finally {
//            cacheContext.leave();
            log.useSource(prev);
            log.popDiagnosticHandler(discardHandler);
            resolve.restoreAccessbilityChecks();
//            enter.shadowTypeEnvs(false);
        }
    }