List of usage examples for java.lang Class getConstructors
@CallerSensitive public Constructor<?>[] getConstructors() throws SecurityException
From source file:com.google.dexmaker.ProxyBuilder.java
/** * Create a new instance of the class to proxy. * /*from w w w . ja v a 2 s .c o m*/ * @throws UnsupportedOperationException * if the class we are trying to create a proxy for is not accessible. * @throws IOException * if an exception occurred writing to the {@code dexCache} directory. * @throws UndeclaredThrowableException * if the constructor for the base class to proxy throws a declared exception during construction. * @throws IllegalArgumentException * if the handler is null, if the constructor argument types do not match the constructor argument values, or if no such constructor exists. */ public T build(Application application) throws IOException { this.application = application; if (handler == null) { throw new IllegalArgumentException("handler == null"); } if (constructorArgTypes.length != constructorArgValues.length) { throw new IllegalArgumentException("constructorArgValues.length != constructorArgTypes.length"); } Class<? extends T> proxyClass = buildProxyClass(); if (proxyClass == null) { return null; } Constructor<? extends T> constructor = null; try { constructor = proxyClass.getConstructor(constructorArgTypes); } catch (NoSuchMethodException e) { Constructor[] constructors = proxyClass.getConstructors(); for (Constructor constructor2 : constructors) { if (constructor2.getGenericParameterTypes().length == constructorArgTypes.length) { constructor = constructor2; break; } } } T result; try { result = constructor.newInstance(constructorArgValues); } catch (InstantiationException e) { // Should not be thrown, generated class is not abstract. throw new AssertionError(e); } catch (IllegalAccessException e) { // Should not be thrown, the generated constructor is accessible. throw new AssertionError(e); } catch (InvocationTargetException e) { // Thrown when the base class constructor throws an exception. throw launderCause(e); } setHandlerInstanceField(result, handler); return result; }
From source file:com.gargoylesoftware.htmlunit.CodeStyleTest.java
private void testTests(final File dir) throws Exception { for (final File file : dir.listFiles()) { if (file.isDirectory()) { if (!".svn".equals(file.getName())) { testTests(file);/*from w w w .j av a2s. com*/ } } else { if (file.getName().endsWith(".java")) { final int index = new File("src/test/java").getAbsolutePath().length(); String name = file.getAbsolutePath(); name = name.substring(index + 1, name.length() - 5); name = name.replace(File.separatorChar, '.'); final Class<?> clazz; try { clazz = Class.forName(name); } catch (final Exception e) { continue; } name = file.getName(); if (name.endsWith("Test.java") || name.endsWith("TestCase.java")) { for (final Constructor<?> ctor : clazz.getConstructors()) { if (ctor.getParameterTypes().length == 0) { for (final Method method : clazz.getDeclaredMethods()) { if (Modifier.isPublic(method.getModifiers()) && method.getAnnotation(Before.class) == null && method.getAnnotation(BeforeClass.class) == null && method.getAnnotation(After.class) == null && method.getAnnotation(AfterClass.class) == null && method.getAnnotation(Test.class) == null && method.getReturnType() == Void.TYPE && method.getParameterTypes().length == 0) { fail("Method '" + method.getName() + "' in " + name + " does not declare @Test annotation"); } } } } } } } } }
From source file:org.springframework.beans.factory.support.ConstructorResolver.java
/** * "autowire constructor" (with constructor arguments by type) behavior. * Also applied if explicit constructor argument values are specified, * matching all remaining arguments with beans from the bean factory. * <p>This corresponds to constructor injection: In this mode, a Spring * bean factory is able to host components that expect constructor-based * dependency resolution.//from w w w. j a v a2 s . c o m * @param beanName the name of the bean * @param mbd the merged bean definition for the bean * @param chosenCtors chosen candidate constructors (or {@code null} if none) * @param explicitArgs argument values passed in programmatically via the getBean method, * or {@code null} if none (-> use constructor argument values from bean definition) * @return a BeanWrapper for the new instance */ public BeanWrapper autowireConstructor(final String beanName, final RootBeanDefinition mbd, @Nullable Constructor<?>[] chosenCtors, @Nullable final Object[] explicitArgs) { BeanWrapperImpl bw = new BeanWrapperImpl(); this.beanFactory.initBeanWrapper(bw); Constructor<?> constructorToUse = null; ArgumentsHolder argsHolderToUse = null; Object[] argsToUse = null; if (explicitArgs != null) { argsToUse = explicitArgs; } else { Object[] argsToResolve = null; synchronized (mbd.constructorArgumentLock) { constructorToUse = (Constructor<?>) mbd.resolvedConstructorOrFactoryMethod; if (constructorToUse != null && mbd.constructorArgumentsResolved) { // Found a cached constructor... argsToUse = mbd.resolvedConstructorArguments; if (argsToUse == null) { argsToResolve = mbd.preparedConstructorArguments; } } } if (argsToResolve != null) { argsToUse = resolvePreparedArguments(beanName, mbd, bw, constructorToUse, argsToResolve, true); } } if (constructorToUse == null) { // Need to resolve the constructor. boolean autowiring = (chosenCtors != null || mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_CONSTRUCTOR); ConstructorArgumentValues resolvedValues = null; int minNrOfArgs; if (explicitArgs != null) { minNrOfArgs = explicitArgs.length; } else { ConstructorArgumentValues cargs = mbd.getConstructorArgumentValues(); resolvedValues = new ConstructorArgumentValues(); minNrOfArgs = resolveConstructorArguments(beanName, mbd, bw, cargs, resolvedValues); } // Take specified constructors, if any. Constructor<?>[] candidates = chosenCtors; if (candidates == null) { Class<?> beanClass = mbd.getBeanClass(); try { candidates = (mbd.isNonPublicAccessAllowed() ? beanClass.getDeclaredConstructors() : beanClass.getConstructors()); } catch (Throwable ex) { throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Resolution of declared constructors on bean Class [" + beanClass.getName() + "] from ClassLoader [" + beanClass.getClassLoader() + "] failed", ex); } } AutowireUtils.sortConstructors(candidates); int minTypeDiffWeight = Integer.MAX_VALUE; Set<Constructor<?>> ambiguousConstructors = null; LinkedList<UnsatisfiedDependencyException> causes = null; for (Constructor<?> candidate : candidates) { Class<?>[] paramTypes = candidate.getParameterTypes(); if (constructorToUse != null && argsToUse.length > paramTypes.length) { // Already found greedy constructor that can be satisfied -> // do not look any further, there are only less greedy constructors left. break; } if (paramTypes.length < minNrOfArgs) { continue; } ArgumentsHolder argsHolder; if (resolvedValues != null) { try { String[] paramNames = ConstructorPropertiesChecker.evaluate(candidate, paramTypes.length); if (paramNames == null) { ParameterNameDiscoverer pnd = this.beanFactory.getParameterNameDiscoverer(); if (pnd != null) { paramNames = pnd.getParameterNames(candidate); } } argsHolder = createArgumentArray(beanName, mbd, resolvedValues, bw, paramTypes, paramNames, getUserDeclaredConstructor(candidate), autowiring, candidates.length == 1); } catch (UnsatisfiedDependencyException ex) { if (logger.isTraceEnabled()) { logger.trace( "Ignoring constructor [" + candidate + "] of bean '" + beanName + "': " + ex); } // Swallow and try next constructor. if (causes == null) { causes = new LinkedList<>(); } causes.add(ex); continue; } } else { // Explicit arguments given -> arguments length must match exactly. if (paramTypes.length != explicitArgs.length) { continue; } argsHolder = new ArgumentsHolder(explicitArgs); } int typeDiffWeight = (mbd.isLenientConstructorResolution() ? argsHolder.getTypeDifferenceWeight(paramTypes) : argsHolder.getAssignabilityWeight(paramTypes)); // Choose this constructor if it represents the closest match. if (typeDiffWeight < minTypeDiffWeight) { constructorToUse = candidate; argsHolderToUse = argsHolder; argsToUse = argsHolder.arguments; minTypeDiffWeight = typeDiffWeight; ambiguousConstructors = null; } else if (constructorToUse != null && typeDiffWeight == minTypeDiffWeight) { if (ambiguousConstructors == null) { ambiguousConstructors = new LinkedHashSet<>(); ambiguousConstructors.add(constructorToUse); } ambiguousConstructors.add(candidate); } } if (constructorToUse == null) { if (causes != null) { UnsatisfiedDependencyException ex = causes.removeLast(); for (Exception cause : causes) { this.beanFactory.onSuppressedException(cause); } throw ex; } throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Could not resolve matching constructor " + "(hint: specify index/type/name arguments for simple parameters to avoid type ambiguities)"); } else if (ambiguousConstructors != null && !mbd.isLenientConstructorResolution()) { throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Ambiguous constructor matches found in bean '" + beanName + "' " + "(hint: specify index/type/name arguments for simple parameters to avoid type ambiguities): " + ambiguousConstructors); } if (explicitArgs == null) { argsHolderToUse.storeCache(mbd, constructorToUse); } } try { final InstantiationStrategy strategy = this.beanFactory.getInstantiationStrategy(); Object beanInstance; if (System.getSecurityManager() != null) { final Constructor<?> ctorToUse = constructorToUse; final Object[] argumentsToUse = argsToUse; beanInstance = AccessController .doPrivileged( (PrivilegedAction<Object>) () -> strategy.instantiate(mbd, beanName, this.beanFactory, ctorToUse, argumentsToUse), this.beanFactory.getAccessControlContext()); } else { beanInstance = strategy.instantiate(mbd, beanName, this.beanFactory, constructorToUse, argsToUse); } bw.setBeanInstance(beanInstance); return bw; } catch (Throwable ex) { throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Bean instantiation via constructor failed", ex); } }
From source file:org.opendaylight.netvirt.openstack.netvirt.impl.NeutronL3AdapterTest.java
@SuppressWarnings("rawtypes") private Object createFloatingIpObject() throws Exception { Class clazz = Whitebox.getInnerClassType(NeutronL3Adapter.class, "FloatIpData"); Constructor[] constructors = clazz.getConstructors(); Constructor c = constructors[0]; return c.newInstance(neutronL3Adapter, 415L, 415L, "a", "b", "c", "d", "e"); }
From source file:org.sipfoundry.sipxconfig.commserver.imdb.ReplicationManagerImpl.java
private synchronized void doParallelReplication(int membersCount, Class<? extends ReplicationWorker> cls, Object type) {//from www.j a va 2s . c o m ExecutorService replicationExecutorService = Executors.newFixedThreadPool(m_nThreads); Long start = System.currentTimeMillis(); int pageSize = m_pageSize; if (m_useDynamicPageSize) { pageSize = membersCount / m_nThreads + 1; } int pages = new Double(Math.ceil(membersCount / pageSize)).intValue() + 1; Constructor<? extends ReplicationWorker> ct = (Constructor<? extends ReplicationWorker>) cls .getConstructors()[0]; List<Future<Void>> futures = new ArrayList<Future<Void>>(); LOG.info("Starting parallel regeneration of mongo group of " + membersCount + " entities on " + m_nThreads + " threads using chunks of " + pageSize + " users"); for (int i = 0; i < pages; i++) { ReplicationWorker worker = null; try { worker = ct.newInstance(this, i * pageSize, pageSize, type); } catch (InstantiationException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } futures.add(replicationExecutorService.submit(worker)); } for (Future<Void> future : futures) { try { future.get(); } catch (InterruptedException e) { throw new RuntimeException(e); } catch (ExecutionException e) { throw new RuntimeException(e); } } replicationExecutorService.shutdown(); Long end = System.currentTimeMillis(); LOG.info("Regeneration of entities finished in " + (end - start) / 1000 + SECONDS + (end - start) / 1000 / 60 + MINUTES); }
From source file:org.talend.daikon.properties.PropertiesImpl.java
@Override public NamedThing createPropertyInstance(NamedThing otherProp) throws ReflectiveOperationException { NamedThing thisProp = null;/*w ww.j a v a2s .c om*/ Class<? extends NamedThing> otherClass = otherProp.getClass(); if (Property.class.isAssignableFrom(otherClass)) { Property<?> otherPy = (Property<?>) otherProp; Constructor<? extends NamedThing> c = otherClass.getDeclaredConstructor(String.class, String.class); c.setAccessible(true); thisProp = c.newInstance(otherPy.getType(), otherPy.getName()); } else if (Properties.class.isAssignableFrom(otherClass)) { // Look for single arg String, but an inner class will have a Properties as first arg Constructor<?>[] constructors = otherClass.getConstructors(); for (Constructor<?> c : constructors) { Class<?> pts[] = c.getParameterTypes(); c.setAccessible(true); if (pts.length == 1 && String.class.isAssignableFrom(pts[0])) { thisProp = (NamedThing) c.newInstance(otherProp.getName()); break; } if (pts.length == 2 && Properties.class.isAssignableFrom(pts[0]) && String.class.isAssignableFrom(pts[1])) { thisProp = (NamedThing) c.newInstance(this, otherProp.getName()); break; } } if (thisProp == null) { TalendRuntimeException.unexpectedException( "Failed to find a proper constructor in Properties : " + otherClass.getName()); } } else { TalendRuntimeException.unexpectedException( "Unexpected property class: " + otherProp.getClass() + " prop: " + otherProp); } return thisProp; }
From source file:com.hubcap.task.TaskRunner.java
/** * Spawns a TaskRunnerHelper which performs some task in aggregation of the * data we want. Sometimes there is only a single helper. But for scavenger * mode, etc there can be many. The helperPool supports multiple for that * reason./*from w ww . j av a2 s. c o m*/ * * @param helper */ protected TaskRunnerHelper spawnHelper(Class<? extends TaskRunnerHelper> clazz, SearchHelperListener listener) { try { Constructor<?> c = clazz.getConstructors()[0]; TaskRunnerHelper helper = (TaskRunnerHelper) c.newInstance(sewingMachine, this); try { helperPool.execute(helper); this.helpers.add(helper); helper.setListener(listener); return helper; } catch (RejectedExecutionException ex) { System.err.println("Failed to execute thread at: " + this.helpers.size()); ErrorUtils.printStackTrace(ex); } helper.die(); } catch (IllegalAccessException ex) { ErrorUtils.printStackTrace(ex); } catch (InstantiationException ex) { ErrorUtils.printStackTrace(ex); } catch (InvocationTargetException ex) { ErrorUtils.printStackTrace(ex); } return null; }
From source file:org.eclipse.winery.repository.backend.filebased.FilebasedRepository.java
@Override public <T extends TOSCAElementId> SortedSet<T> getNestedIds(GenericId ref, Class<T> idClass) { Path dir = this.id2AbsolutePath(ref); SortedSet<T> res = new TreeSet<T>(); if (!Files.exists(dir)) { // the id has been generated by the exporter without existance test. // This test is done here. return res; }//from www.j av a 2s. c om assert (Files.isDirectory(dir)); // list all directories contained in this directory try (DirectoryStream<Path> ds = Files.newDirectoryStream(dir, new OnlyNonHiddenDirectories())) { for (Path p : ds) { XMLId xmlId = new XMLId(p.getFileName().toString(), true); @SuppressWarnings("unchecked") Constructor<T>[] constructors = (Constructor<T>[]) idClass.getConstructors(); assert (constructors.length == 1); Constructor<T> constructor = constructors[0]; assert (constructor.getParameterTypes().length == 2); T id; try { id = constructor.newInstance(ref, xmlId); } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { FilebasedRepository.logger.debug("Internal error at invocation of id constructor", e); // abort everything, return invalid result return res; } res.add(id); } } catch (IOException e) { FilebasedRepository.logger.debug("Cannot close ds", e); } return res; }
From source file:org.kepler.objectmanager.ActorMetadata.java
/** * createInstance. creates an instance of a class object. taken from * ptolemy's MomlParser class. modified for this application. * /*ww w . j av a 2s. co m*/ * @param newClass *@param arguments *@return TypedAtomicActor *@exception Exception */ public static NamedObj createInstance(Class<?> newClass, Object[] arguments) throws Exception { if (isDebugging) log.debug("createInstance(" + newClass + "," + arguments + ")"); Constructor<?>[] constructors = newClass.getConstructors(); for (int i = 0; i < constructors.length; i++) { Constructor<?> constructor = constructors[i]; Class<?>[] parameterTypes = constructor.getParameterTypes(); for (int j = 0; j < parameterTypes.length; j++) { Class<?> c = parameterTypes[j]; if (isDebugging) log.debug(c.getName()); } if (parameterTypes.length != arguments.length) { continue; } boolean match = true; for (int j = 0; j < parameterTypes.length; j++) { if (!(parameterTypes[j].isInstance(arguments[j]))) { match = false; break; } } if (match) { NamedObj newEntity = (NamedObj) constructor.newInstance(arguments); return newEntity; } } // If we get here, then there is no matching constructor. // Generate a StringBuffer containing what we were looking for. StringBuffer argumentBuffer = new StringBuffer(); for (int i = 0; i < arguments.length; i++) { argumentBuffer.append(arguments[i].getClass() + " = \"" + arguments[i].toString() + "\""); if (i < (arguments.length - 1)) { argumentBuffer.append(", "); } } throw new Exception("Cannot find a suitable constructor (" + arguments.length + " args) (" + argumentBuffer + ") for '" + newClass.getName() + "'"); }
From source file:org.apache.myfaces.config.FacesConfigurator.java
/** * A mapper for the handful of system listener defaults * since every default mapper has the source type embedded * in the constructor we can rely on introspection for the * default mapping/*ww w.j av a 2s .c o m*/ * * @param systemEventClass the system listener class which has to be checked * @return */ String getDefaultSourcClassForSystemEvent(Class systemEventClass) { Constructor[] constructors = systemEventClass.getConstructors(); for (Constructor constr : constructors) { Class[] parms = constr.getParameterTypes(); if (parms == null || parms.length != 1) { //for standard types we have only one parameter representing the type continue; } return parms[0].getName(); } log.warning("The SystemEvent source type for " + systemEventClass.getName() + " could not be detected, either register it manually or use a constructor argument " + "for auto detection, defaulting now to java.lang.Object"); return "java.lang.Object"; }