java.lang.reflect.Constructor Java Examples

The following examples show how to use java.lang.reflect.Constructor. 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
Source File: WebappLoader.java    From Tomcat7.0.67 with 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 #2
Source File: BytecodeGen.java    From businessworks with 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 #3
Source File: CRLExtensions.java    From Bytecoder with 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 #4
Source File: OBISMessage.java    From openhab1-addons with 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 #5
Source File: ConfigDefaultMethod.java    From cuba with 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 #6
Source File: ModelMBeanConstructorInfo.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
    * 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 #7
Source File: CanvasApiFactory.java    From canvas-api with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * 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 #8
Source File: Java8TimeSerializer.java    From jvm-sandbox-repeater with 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 #9
Source File: Main.java    From openjdk-jdk9 with 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 #10
Source File: MobileDriver.java    From ats-framework with 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 #11
Source File: ReflectionUtils.java    From embedded-database-spring-test with Apache License 2.0 6 votes vote down vote up
@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 #12
Source File: WebappLoader.java    From Tomcat8-Source-Read with 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 #13
Source File: TimeUtilsTest.java    From spring-boot-email-tools with 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 #14
Source File: ORMUtils.java    From das with 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 #15
Source File: Connection.java    From jdk8u60 with 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 #16
Source File: Util.java    From Bytecoder with 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 #17
Source File: AbstractDataGridLoader.java    From cuba with 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 #18
Source File: AssistedConstructor.java    From crate with 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 #19
Source File: DirectInstantiator.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
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 #20
Source File: SimpleComponentHolder.java    From ucar-weex-core with 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 #21
Source File: MetaFetcherManager.java    From DBus with 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 #22
Source File: BigdataSailFactory.java    From database with 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 #23
Source File: RepositoryProvider.java    From jackrabbit-filevault with 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 #24
Source File: ProxyArrays.java    From hottub with 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 #25
Source File: BootstrapUtils.java    From spring4-understanding with 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 #26
Source File: AnnotationUtils.java    From Paginize with 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 #27
Source File: ConstructorReference.java    From spring-analysis-note with 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 #28
Source File: GridUtilityTest.java    From Selenium-Foundation with 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 #29
Source File: ConstructorLookupCache.java    From emissary with 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 #30
Source File: Instance.java    From MaxKey with Apache License 2.0 5 votes vote down vote up
public static Object newInstance(String className) {
	Class<?> cls;
	try {
		cls = Class.forName(className);
		Constructor<?> constructor = cls.getConstructor();
		return constructor.newInstance();
	} catch (Exception e) {
		e.printStackTrace();
	}
	return null;

}