List of usage examples for java.lang Class getDeclaredConstructors
@CallerSensitive public Constructor<?>[] getDeclaredConstructors() throws SecurityException
From source file:com.smartitengineering.generator.engine.service.impl.ReportConfigServiceImpl.java
@Inject public void initCrons() { logger.info("Initialize cron jobs"); try {/*from w ww . ja va 2 s . c o m*/ scheduler = StdSchedulerFactory.getDefaultScheduler(); JobDetail detail = new JobDetail("reportSyncJob", "reportSyncPoll", EventSyncJob.class); Trigger trigger = new DateIntervalTrigger("reportSyncTrigger", "reportSyncPoll", DateIntervalTrigger.IntervalUnit.MINUTE, 5); JobDetail redetail = new JobDetail("reportReSyncJob", "reportReSyncPoll", EventReSyncJob.class); Trigger retrigger = new DateIntervalTrigger("reportReSyncTrigger", "reportReSyncPoll", DateIntervalTrigger.IntervalUnit.DAY, 1); JobDetail reportDetail = new JobDetail("reportJob", "reportPoll", ReportJob.class); Trigger reportTrigger = new DateIntervalTrigger("reportTrigger", "reportPoll", DateIntervalTrigger.IntervalUnit.MINUTE, 1); scheduler.setJobFactory(new JobFactory() { public Job newJob(TriggerFiredBundle bundle) throws SchedulerException { try { Class<? extends Job> jobClass = bundle.getJobDetail().getJobClass(); if (ReportConfigServiceImpl.class.equals(jobClass.getEnclosingClass())) { Constructor<? extends Job> constructor = (Constructor<? extends Job>) jobClass .getDeclaredConstructors()[0]; constructor.setAccessible(true); Job job = constructor.newInstance(ReportConfigServiceImpl.this); return job; } else { return jobClass.newInstance(); } } catch (Exception ex) { throw new SchedulerException(ex); } } }); scheduler.start(); scheduler.scheduleJob(detail, trigger); scheduler.scheduleJob(redetail, retrigger); scheduler.scheduleJob(reportDetail, reportTrigger); } catch (Exception ex) { logger.warn("Could initialize cron job!", ex); } }
From source file:com.payu.sdk.util.UtilTest.java
/** * Private constructor test// ww w . j a v a 2 s .c om * * @param clasz * @throws IllegalArgumentException * @throws InstantiationException * @throws IllegalAccessException * @throws InvocationTargetException */ @SuppressWarnings("rawtypes") private void privateConstructorTest(Class clasz) throws IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException { Constructor[] ctors = clasz.getDeclaredConstructors(); Assert.assertEquals(1, ctors.length, "Utility class should only have one constructor"); Constructor ctor = ctors[0]; Assert.assertFalse(ctor.isAccessible(), "Utility class constructor should be inaccessible"); ctor.setAccessible(true); // obviously we'd never do this in production Assert.assertEquals(clasz, ctor.newInstance().getClass(), "You'd expect the construct to return the expected type"); }
From source file:org.robospring.inject.RoboSpringInjector.java
@Override public Constructor<?>[] determineCandidateConstructors(Class<?> beanClass, String beanName) throws BeansException { // Quick check on the concurrent map first, with minimal locking. Constructor<?>[] candidateConstructors = this.candidateConstructorsCache.get(beanClass); if (candidateConstructors == null) { synchronized (this.candidateConstructorsCache) { candidateConstructors = this.candidateConstructorsCache.get(beanClass); if (candidateConstructors == null) { Constructor<?>[] rawCandidates = beanClass.getDeclaredConstructors(); List<Constructor<?>> candidates = new ArrayList<Constructor<?>>(rawCandidates.length); Constructor<?> requiredConstructor = null; Constructor<?> defaultConstructor = null; for (Constructor<?> candidate : rawCandidates) { Annotation annotation = findAutowiredAnnotation(candidate); if (annotation != null) { if (requiredConstructor != null) { throw new BeanCreationException("Invalid autowire-marked constructor: " + candidate + ". Found another constructor with 'required' Autowired annotation: " + requiredConstructor); }// w w w.jav a 2 s . co m if (candidate.getParameterTypes().length == 0) { throw new IllegalStateException( "Autowired annotation requires at least one argument: " + candidate); } boolean required = determineRequiredStatus(annotation); if (required) { if (!candidates.isEmpty()) { throw new BeanCreationException("Invalid autowire-marked constructors: " + candidates + ". Found another constructor with 'required' Autowired annotation: " + requiredConstructor); } requiredConstructor = candidate; } candidates.add(candidate); } else if (candidate.getParameterTypes().length == 0) { defaultConstructor = candidate; } } if (!candidates.isEmpty()) { // Add default constructor to list of optional // constructors, as fallback. if (requiredConstructor == null && defaultConstructor != null) { candidates.add(defaultConstructor); } candidateConstructors = candidates.toArray(new Constructor[candidates.size()]); } else { candidateConstructors = new Constructor[0]; } this.candidateConstructorsCache.put(beanClass, candidateConstructors); } } } return (candidateConstructors.length > 0 ? candidateConstructors : null); }
From source file:net.stickycode.mockwire.spring30.MockwireFieldInjectionAnnotationBeanPostProcessor.java
@Override public Constructor[] determineCandidateConstructors(Class beanClass, String beanName) throws BeansException { // Quick check on the concurrent map first, with minimal locking. Constructor[] candidateConstructors = this.candidateConstructorsCache.get(beanClass); if (candidateConstructors == null) { synchronized (this.candidateConstructorsCache) { candidateConstructors = this.candidateConstructorsCache.get(beanClass); if (candidateConstructors == null) { Constructor[] rawCandidates = beanClass.getDeclaredConstructors(); List<Constructor> candidates = new ArrayList<Constructor>(rawCandidates.length); Constructor requiredConstructor = null; Constructor defaultConstructor = null; for (Constructor<?> candidate : rawCandidates) { Annotation annotation = findAutowiredAnnotation(candidate); if (annotation != null) { if (requiredConstructor != null) { throw new BeanCreationException("Invalid autowire-marked constructor: " + candidate + ". Found another constructor with 'required' Autowired annotation: " + requiredConstructor); }//from www.j a va2s . c o m if (candidate.getParameterTypes().length == 0) { throw new IllegalStateException( "Autowired annotation requires at least one argument: " + candidate); } boolean required = determineRequiredStatus(annotation); if (required) { if (!candidates.isEmpty()) { throw new BeanCreationException("Invalid autowire-marked constructors: " + candidates + ". Found another constructor with 'required' Autowired annotation: " + requiredConstructor); } requiredConstructor = candidate; } candidates.add(candidate); } else if (candidate.getParameterTypes().length == 0) { defaultConstructor = candidate; } } if (!candidates.isEmpty()) { // Add default constructor to list of optional constructors, as fallback. if (requiredConstructor == null && defaultConstructor != null) { candidates.add(defaultConstructor); } candidateConstructors = candidates.toArray(new Constructor[candidates.size()]); } else { candidateConstructors = new Constructor[0]; } this.candidateConstructorsCache.put(beanClass, candidateConstructors); } } } return (candidateConstructors.length > 0 ? candidateConstructors : null); }
From source file:io.realm.Realm.java
/** * Returns the default Realm module. This module contains all Realm classes in the current project, but not * those from library or project dependencies. Realm classes in these should be exposed using their own module. * * @return The default Realm module or null if no default module exists. * @see io.realm.RealmConfiguration.Builder#setModules(Object, Object...) *///from w ww . j av a 2 s . c o m public static Object getDefaultModule() { String moduleName = "io.realm.DefaultRealmModule"; Class<?> clazz; try { clazz = Class.forName(moduleName); Constructor<?> constructor = clazz.getDeclaredConstructors()[0]; constructor.setAccessible(true); return constructor.newInstance(); } catch (ClassNotFoundException e) { return null; } catch (InvocationTargetException e) { throw new RealmException("Could not create an instance of " + moduleName, e); } catch (InstantiationException e) { throw new RealmException("Could not create an instance of " + moduleName, e); } catch (IllegalAccessException e) { throw new RealmException("Could not create an instance of " + moduleName, e); } }
From source file:com.stratuscom.harvester.deployer.StarterServiceDeployer.java
private Object instantiateService(ClassLoader cl, String className, String[] parms) throws ClassNotFoundException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, InstantiationException { Class clazz = Class.forName(className, true, cl); log.log(Level.FINE, MessageNames.CLASSLOADER_IS, new Object[] { clazz.getName(), clazz.getClassLoader().toString() }); // Get this through dynamic lookup becuase it won't be in the parent // classloader! Class lifeCycleClass = Class.forName(Strings.LIFECYCLE_CLASS, true, cl); Constructor[] constructors = clazz.getDeclaredConstructors(); System.out.println("Class is " + clazz); for (int i = 0; i < constructors.length; i++) { Constructor constructor = constructors[i]; System.out.println("Found constructor " + constructor + " on " + className); }/*from w w w.j a v a 2s .c om*/ Constructor constructor = clazz.getDeclaredConstructor(new Class[] { String[].class, lifeCycleClass }); constructor.setAccessible(true); return constructor.newInstance(parms, null); }
From source file:dinistiq.Dinistiq.java
/** * Creates an instance of the given type and registeres it with the container. * * @param dependencies dependencies within the scope * @param cls type to create an instance of * @param beanName beans name in the scope using the given dependencies *//* w w w. j av a 2 s. co m*/ private <T extends Object> T createInstance(Map<String, Set<Object>> dependencies, Class<T> cls, String beanName) throws Exception { LOG.info("createInstance({})", cls.getSimpleName()); Constructor<?> c = null; Constructor<?>[] constructors = cls.getDeclaredConstructors(); LOG.debug("createInstance({}) constructors.length={}", cls.getSimpleName(), constructors.length); for (Constructor<?> ctor : constructors) { LOG.debug("createInstance({}) {}", cls.getSimpleName(), ctor); c = (ctor.getAnnotation(Inject.class) != null) ? ctor : c; } // for c = (c == null) ? cls.getConstructor() : c; // Don't record constructor dependencies - they MUST be already fulfilled Object[] parameters = getParameters(null, null, beanName, c.getParameterTypes(), c.getGenericParameterTypes(), c.getParameterAnnotations()); dependencies.put(beanName, new HashSet<>()); boolean accessible = c.isAccessible(); try { c.setAccessible(true); return convert(c.newInstance(parameters)); } finally { c.setAccessible(accessible); } // try/finally }
From source file:org.springframework.batch.core.jsr.configuration.support.SpringAutowiredAnnotationBeanPostProcessor.java
@Override public Constructor<?>[] determineCandidateConstructors(Class<?> beanClass, String beanName) throws BeansException { // Quick check on the concurrent map first, with minimal locking. Constructor<?>[] candidateConstructors = this.candidateConstructorsCache.get(beanClass); if (candidateConstructors == null) { synchronized (this.candidateConstructorsCache) { candidateConstructors = this.candidateConstructorsCache.get(beanClass); if (candidateConstructors == null) { Constructor<?>[] rawCandidates = beanClass.getDeclaredConstructors(); List<Constructor<?>> candidates = new ArrayList<Constructor<?>>(rawCandidates.length); Constructor<?> requiredConstructor = null; Constructor<?> defaultConstructor = null; for (Constructor<?> candidate : rawCandidates) { Annotation annotation = findAutowiredAnnotation(candidate); if (annotation != null) { if (requiredConstructor != null) { throw new BeanCreationException("Invalid autowire-marked constructor: " + candidate + ". Found another constructor with 'required' Autowired annotation: " + requiredConstructor); }/* w ww . j a v a 2 s . c om*/ if (candidate.getParameterTypes().length == 0) { throw new IllegalStateException( "Autowired annotation requires at least one argument: " + candidate); } boolean required = determineRequiredStatus(annotation); if (required) { if (!candidates.isEmpty()) { throw new BeanCreationException("Invalid autowire-marked constructors: " + candidates + ". Found another constructor with 'required' Autowired annotation: " + requiredConstructor); } requiredConstructor = candidate; } candidates.add(candidate); } else if (candidate.getParameterTypes().length == 0) { defaultConstructor = candidate; } } if (!candidates.isEmpty()) { // Add default constructor to list of optional constructors, as fallback. if (requiredConstructor == null && defaultConstructor != null) { candidates.add(defaultConstructor); } candidateConstructors = candidates.toArray(new Constructor[candidates.size()]); } else { candidateConstructors = new Constructor[0]; } this.candidateConstructorsCache.put(beanClass, candidateConstructors); } } } return (candidateConstructors.length > 0 ? candidateConstructors : null); }
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.// w w w .j a va 2s . co 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:gdt.data.entity.facet.ExtensionHandler.java
/** * Get the handler instance. /*from ww w .ja va 2 s. c o m*/ * @param entigrator entigrator instance * @param extension$ extension key * @param handlerClass$ class name * @return handler instance. */ public static Object loadHandlerInstance(Entigrator entigrator, String extension$, String handlerClass$) { try { System.out.println( "ExtensionHandler:loadHandlerInstance:extension=" + extension$ + " handler=" + handlerClass$); Object obj = null; Class<?> cls = entigrator.getClass(handlerClass$); if (cls == null) { System.out.println("ExtensionHandler:loadHandlerInstance:1"); Sack extension = entigrator.getEntityAtKey(extension$); String lib$ = extension.getElementItemAt("field", "lib"); String jar$ = "jar:file:" + entigrator.getEntihome() + "/" + extension$ + "/" + lib$ + "!/"; ArrayList<URL> urll = new ArrayList<URL>(); urll.add(new URL(jar$)); String[] sa = extension.elementListNoSorted("external"); if (sa != null) { File file; for (String s : sa) { file = new File(entigrator.getEntihome() + "/" + extension$ + "/" + s); if (file.exists()) urll.add(new URL("jar:file:" + file.getPath() + "!/")); } } URL[] urls = urll.toArray(new URL[0]); URLClassLoader cl = URLClassLoader.newInstance(urls); // Class<?>cls=entigrator.getClass(handlerClass$); cls = cl.loadClass(handlerClass$); if (cls == null) { System.out.println("ExtensionHandler:loadHandlerInstance:cannot load class =" + handlerClass$); return null; } else { // System.out.println("ExtensionHandler:loadHandlerInstance:found class ="+handlerClass$); entigrator.putClass(handlerClass$, cls); } } try { Constructor[] ctors = cls.getDeclaredConstructors(); System.out.println("ExtensionHandler:loadHandlerInstance:ctors=" + ctors.length); Constructor ctor = null; for (int i = 0; i < ctors.length; i++) { ctor = ctors[i]; if (ctor.getGenericParameterTypes().length == 0) break; } ctor.setAccessible(true); obj = ctor.newInstance(); } catch (java.lang.NoClassDefFoundError ee) { System.out.println("ExtensionHandler:loadHandlerInstance:" + ee.toString()); return null; } //if(obj!=null) System.out.println("ExtensionHandler:loadHandlerInstance:obj=" + obj.getClass().getName()); return obj; } catch (Exception e) { Logger.getLogger(ExtensionHandler.class.getName()).severe(e.toString()); return null; } }