List of usage examples for java.lang.reflect Constructor getParameterTypes
@Override
public Class<?>[] getParameterTypes()
From source file:org.opencms.search.CmsSearchManager.java
/** * Returns an analyzer for the given class name.<p> * /* w w w. jav a 2 s . c o m*/ * Since Lucene 3.0, many analyzers require a "version" parameter in the constructor and * can not be created by a simple <code>newInstance()</code> call. * This method will create analyzers by name for the {@link CmsSearchIndex#LUCENE_VERSION} version.<p> * * @param className the class name of the analyzer * @param stemmer the optional stemmer parameter required for the snowball analyzer * * @return the appropriate lucene analyzer * * @throws Exception if something goes wrong * * @deprecated The stemmer parameter is used only by the snownall analyzer, which is deprecated in Lucene 3. */ @Deprecated public static Analyzer getAnalyzer(String className, String stemmer) throws Exception { Analyzer analyzer = null; Class<?> analyzerClass; try { analyzerClass = Class.forName(className); } catch (ClassNotFoundException e) { // allow Lucene standard classes to be written in a short form analyzerClass = Class.forName(LUCENE_ANALYZER + className); } // since Lucene 3.0 most analyzers need a "version" parameter and don't support an empty constructor if (StandardAnalyzer.class.equals(analyzerClass)) { // the Lucene standard analyzer is used analyzer = new StandardAnalyzer(CmsSearchIndex.LUCENE_VERSION); } else if (CmsGallerySearchAnalyzer.class.equals(analyzerClass)) { // OpenCms gallery multiple language analyzer analyzer = new CmsGallerySearchAnalyzer(CmsSearchIndex.LUCENE_VERSION); } else { boolean hasEmpty = false; boolean hasVersion = false; boolean hasVersionWithString = false; // another analyzer is used, check if we find a suitable constructor Constructor<?>[] constructors = analyzerClass.getConstructors(); for (int i = 0; i < constructors.length; i++) { Constructor<?> c = constructors[i]; Class<?>[] parameters = c.getParameterTypes(); if (parameters.length == 0) { // an empty constructor has been found hasEmpty = true; } if ((parameters.length == 1) && parameters[0].equals(Version.class)) { // a constructor with a Lucene version parameter has been found hasVersion = true; } if ((stemmer != null) && (parameters.length == 2) && parameters[0].equals(Version.class) && parameters[1].equals(String.class)) { // a constructor with a Lucene version parameter and a String has been found hasVersionWithString = true; } } if (hasVersionWithString) { // a constructor with a Lucene version parameter and a String has been found analyzer = (Analyzer) analyzerClass .getDeclaredConstructor(new Class[] { Version.class, String.class }) .newInstance(CmsSearchIndex.LUCENE_VERSION, stemmer); } else if (hasVersion) { // a constructor with a Lucene version parameter has been found analyzer = (Analyzer) analyzerClass.getDeclaredConstructor(new Class[] { Version.class }) .newInstance(CmsSearchIndex.LUCENE_VERSION); } else if (hasEmpty) { // an empty constructor has been found analyzer = (Analyzer) analyzerClass.newInstance(); } } return analyzer; }
From source file:de.escalon.hypermedia.spring.hydra.LinkListSerializer.java
/** * Writes bean description recursively.// w w w . ja v a 2s .c o m * * @param jgen * to write to * @param currentVocab * in context * @param valueType * class of value * @param allRootParameters * of the method that receives the request body * @param rootParameter * the request body * @param currentCallValue * the value at the current recursion level * @param propertyPath * of the current recursion level * @throws IntrospectionException * @throws IOException */ private void recurseSupportedProperties(JsonGenerator jgen, String currentVocab, Class<?> valueType, ActionDescriptor allRootParameters, ActionInputParameter rootParameter, Object currentCallValue, String propertyPath) throws IntrospectionException, IOException { Map<String, ActionInputParameter> properties = new HashMap<String, ActionInputParameter>(); // collect supported properties from ctor Constructor[] constructors = valueType.getConstructors(); // find default ctor Constructor constructor = PropertyUtils.findDefaultCtor(constructors); // find ctor with JsonCreator ann if (constructor == null) { constructor = PropertyUtils.findJsonCreator(constructors, JsonCreator.class); } if (constructor == null) { // TODO this can be a generic collection, find a way to describe it LOG.warn("can't describe supported properties, no default constructor or JsonCreator found for type " + valueType.getName()); return; } int parameterCount = constructor.getParameterTypes().length; if (parameterCount > 0) { Annotation[][] annotationsOnParameters = constructor.getParameterAnnotations(); Class[] parameters = constructor.getParameterTypes(); int paramIndex = 0; for (Annotation[] annotationsOnParameter : annotationsOnParameters) { for (Annotation annotation : annotationsOnParameter) { if (JsonProperty.class == annotation.annotationType()) { JsonProperty jsonProperty = (JsonProperty) annotation; // TODO use required attribute of JsonProperty String paramName = jsonProperty.value(); Object propertyValue = PropertyUtils.getPropertyOrFieldValue(currentCallValue, paramName); ActionInputParameter constructorParamInputParameter = new SpringActionInputParameter( new MethodParameter(constructor, paramIndex), propertyValue); // TODO collect ctor params, setter params and process // TODO then handle single, collection and bean for both properties.put(paramName, constructorParamInputParameter); paramIndex++; // increase for each @JsonProperty } } } Assert.isTrue(parameters.length == paramIndex, "not all constructor arguments of @JsonCreator " + constructor.getName() + " are annotated with @JsonProperty"); } // collect supported properties from setters // TODO support Option provider by other method args? final BeanInfo beanInfo = Introspector.getBeanInfo(valueType); final PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); // TODO collection and map // TODO distinguish which properties should be printed as supported - now just setters for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { final Method writeMethod = propertyDescriptor.getWriteMethod(); if (writeMethod == null) { continue; } // TODO: the property name must be a valid URI - need to check context for terms? String propertyName = getWritableExposedPropertyOrPropertyName(propertyDescriptor); Object propertyValue = PropertyUtils.getPropertyOrFieldValue(currentCallValue, propertyDescriptor.getName()); MethodParameter methodParameter = new MethodParameter(propertyDescriptor.getWriteMethod(), 0); ActionInputParameter propertySetterInputParameter = new SpringActionInputParameter(methodParameter, propertyValue); properties.put(propertyName, propertySetterInputParameter); } // write all supported properties // TODO we are using the annotatedParameter.parameterName but should use the key of properties here: for (ActionInputParameter annotatedParameter : properties.values()) { String nextPropertyPathLevel = propertyPath.isEmpty() ? annotatedParameter.getParameterName() : propertyPath + '.' + annotatedParameter.getParameterName(); if (DataType.isSingleValueType(annotatedParameter.getParameterType())) { final Object[] possiblePropertyValues = rootParameter.getPossibleValues(allRootParameters); if (rootParameter.isIncluded(nextPropertyPathLevel) && !rootParameter.isExcluded(nextPropertyPathLevel)) { writeSupportedProperty(jgen, currentVocab, annotatedParameter, annotatedParameter.getParameterName(), possiblePropertyValues); } // TODO collections? // } else if (DataType.isArrayOrCollection(parameterType)) { // Object[] callValues = rootParameter.getValues(); // int items = callValues.length; // for (int i = 0; i < items; i++) { // Object value; // if (i < callValues.length) { // value = callValues[i]; // } else { // value = null; // } // recurseSupportedProperties(jgen, currentVocab, rootParameter // .getParameterType(), // allRootParameters, rootParameter, value); // } } else { jgen.writeStartObject(); jgen.writeStringField("hydra:property", annotatedParameter.getParameterName()); // TODO: is the property required -> for bean props we need the Access annotation to express that jgen.writeObjectFieldStart(getPropertyOrClassNameInVocab(currentVocab, "rangeIncludes", LdContextFactory.HTTP_SCHEMA_ORG, "schema:")); Expose expose = AnnotationUtils.getAnnotation(annotatedParameter.getParameterType(), Expose.class); String subClass; if (expose != null) { subClass = expose.value(); } else { subClass = annotatedParameter.getParameterType().getSimpleName(); } jgen.writeStringField(getPropertyOrClassNameInVocab(currentVocab, "subClassOf", "http://www.w3" + ".org/2000/01/rdf-schema#", "rdfs:"), subClass); jgen.writeArrayFieldStart("hydra:supportedProperty"); Object propertyValue = PropertyUtils.getPropertyOrFieldValue(currentCallValue, annotatedParameter.getParameterName()); recurseSupportedProperties(jgen, currentVocab, annotatedParameter.getParameterType(), allRootParameters, rootParameter, propertyValue, nextPropertyPathLevel); jgen.writeEndArray(); jgen.writeEndObject(); jgen.writeEndObject(); } } }
From source file:org.eclipse.wb.internal.core.model.creation.ThisCreationSupport.java
private Object create_usingCGLib(ExecutionFlowFrameVisitor visitor, Constructor<?> constructor, Class<?> componentClass, Object[] argumentValues) { createEnhancer(componentClass, visitor); // set current ASTNode = body of constructor ExecutionFlowDescription flowDescription; {/*from www .ja v a 2 s.c om*/ flowDescription = m_editorState.getFlowDescription(); flowDescription.enterStatement(m_constructor.getBody()); } // create object try { if (constructor != null) { Assert.isTrueException(!ReflectionUtils.isPackagePrivate(constructor), ICoreExceptionConstants.EVAL_NON_PUBLIC_CONSTRUCTOR, constructor); return m_enhancer.create(constructor.getParameterTypes(), argumentValues); } else { return m_enhancer.create(); } } finally { flowDescription.leaveStatement(m_constructor.getBody()); } }
From source file:org.wandora.modules.ModuleManager.java
/** * Parses a single param element and returns its value. Handles all the * different cases of how a param elements value can be determined. * //from w w w . j a v a2 s . co m * @param e The xml param element. * @return The value of the parameter. */ public Object parseXMLParamElement(Element e) throws ReflectiveOperationException, IllegalArgumentException, ScriptException { String instance = e.getAttribute("instance"); if (instance != null && instance.length() > 0) { Class cls = Class.forName(instance); HashMap<String, Object> params = parseXMLOptionsElement(e); if (!params.isEmpty()) { Collection<Object> constructorParams = params.values(); Constructor[] cs = cls.getConstructors(); ConstructorLoop: for (int i = 0; i < cs.length; i++) { Constructor c = cs[i]; Class[] paramTypes = c.getParameterTypes(); if (paramTypes.length != constructorParams.size()) continue; int j = -1; for (Object o : constructorParams) { j++; if (o == null) { if (!paramTypes[j].isPrimitive()) continue; else continue ConstructorLoop; } if (paramTypes[j].isPrimitive()) { if (paramTypes[j] == int.class) { if (o.getClass() != Integer.class) continue ConstructorLoop; } else if (paramTypes[j] == long.class) { if (o.getClass() != Long.class) continue ConstructorLoop; } else if (paramTypes[j] == double.class) { if (o.getClass() != Double.class) continue ConstructorLoop; } else if (paramTypes[j] == float.class) { if (o.getClass() != Float.class) continue ConstructorLoop; } else if (paramTypes[j] == byte.class) { if (o.getClass() != Byte.class) continue ConstructorLoop; } else continue ConstructorLoop; //did we forget some primitive type? } else if (!o.getClass().isAssignableFrom(paramTypes[j])) continue ConstructorLoop; } return c.newInstance(constructorParams.toArray()); } throw new NoSuchMethodException( "Couldn't find a constructor that matches parameters parsed from XML."); } else { return cls.newInstance(); } } String clas = e.getAttribute("class"); if (clas != null && clas.length() > 0) { Class cls = Class.forName(clas); return cls; } if (e.hasAttribute("null")) return null; if (e.hasAttribute("script")) { String engine = e.getAttribute("script"); if (engine.length() == 0 || engine.equalsIgnoreCase("default")) engine = ScriptManager.getDefaultScriptEngine(); ScriptManager scriptManager = new ScriptManager(); ScriptEngine scriptEngine = scriptManager.getScriptEngine(engine); scriptEngine.put("moduleManager", this); scriptEngine.put("element", e); try { String script = ((String) xpath.evaluate("text()", e, XPathConstants.STRING)).trim(); return scriptManager.executeScript(script, scriptEngine); } catch (XPathExpressionException xpee) { throw new RuntimeException(xpee); } } if (e.hasAttribute("module")) { String moduleName = e.getAttribute("module").trim(); return new ModuleDelegate(this, moduleName); } try { String value = ((String) xpath.evaluate("text()", e, XPathConstants.STRING)).trim(); return replaceVariables(value, variables); } catch (XPathExpressionException xpee) { throw new RuntimeException(xpee); } }
From source file:org.apache.myfaces.application.ApplicationImpl.java
private static SystemEvent _createEvent(Class<? extends SystemEvent> systemEventClass, Object source, SystemEvent event) {//from w w w. j a v a2 s. c om if (event == null) { try { Constructor<?>[] constructors = systemEventClass.getConstructors(); Constructor<? extends SystemEvent> constructor = null; for (Constructor<?> c : constructors) { if (c.getParameterTypes().length == 1) { // Safe cast, since the constructor belongs // to a class of type SystemEvent constructor = (Constructor<? extends SystemEvent>) c; break; } } if (constructor != null) { event = constructor.newInstance(source); } } catch (Exception e) { throw new FacesException("Couldn't instanciate system event of type " + systemEventClass.getName(), e); } } return event; }
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 ww . j ava 2 s . com 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.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.java
@Override @Nullable//from ww w .j a v a 2s .com public Constructor<?>[] determineCandidateConstructors(Class<?> beanClass, final String beanName) throws BeanCreationException { // Let's check for lookup methods here.. if (!this.lookupMethodsChecked.contains(beanName)) { try { ReflectionUtils.doWithMethods(beanClass, method -> { Lookup lookup = method.getAnnotation(Lookup.class); if (lookup != null) { Assert.state(beanFactory != null, "No BeanFactory available"); LookupOverride override = new LookupOverride(method, lookup.value()); try { RootBeanDefinition mbd = (RootBeanDefinition) beanFactory .getMergedBeanDefinition(beanName); mbd.getMethodOverrides().addOverride(override); } catch (NoSuchBeanDefinitionException ex) { throw new BeanCreationException(beanName, "Cannot apply @Lookup to beans without corresponding bean definition"); } } }); } catch (IllegalStateException ex) { throw new BeanCreationException(beanName, "Lookup method resolution failed", ex); } this.lookupMethodsChecked.add(beanName); } // Quick check on the concurrent map first, with minimal locking. Constructor<?>[] candidateConstructors = this.candidateConstructorsCache.get(beanClass); if (candidateConstructors == null) { // Fully synchronized resolution now... synchronized (this.candidateConstructorsCache) { candidateConstructors = this.candidateConstructorsCache.get(beanClass); if (candidateConstructors == null) { Constructor<?>[] rawCandidates; try { rawCandidates = beanClass.getDeclaredConstructors(); } catch (Throwable ex) { throw new BeanCreationException(beanName, "Resolution of declared constructors on bean Class [" + beanClass.getName() + "] from ClassLoader [" + beanClass.getClassLoader() + "] failed", ex); } List<Constructor<?>> candidates = new ArrayList<>(rawCandidates.length); Constructor<?> requiredConstructor = null; Constructor<?> defaultConstructor = null; Constructor<?> primaryConstructor = BeanUtils.findPrimaryConstructor(beanClass); int nonSyntheticConstructors = 0; for (Constructor<?> candidate : rawCandidates) { if (!candidate.isSynthetic()) { nonSyntheticConstructors++; } else if (primaryConstructor != null) { continue; } AnnotationAttributes ann = findAutowiredAnnotation(candidate); if (ann == null) { Class<?> userClass = ClassUtils.getUserClass(beanClass); if (userClass != beanClass) { try { Constructor<?> superCtor = userClass .getDeclaredConstructor(candidate.getParameterTypes()); ann = findAutowiredAnnotation(superCtor); } catch (NoSuchMethodException ex) { // Simply proceed, no equivalent superclass constructor found... } } } if (ann != null) { if (requiredConstructor != null) { throw new BeanCreationException(beanName, "Invalid autowire-marked constructor: " + candidate + ". Found constructor with 'required' Autowired annotation already: " + requiredConstructor); } boolean required = determineRequiredStatus(ann); if (required) { if (!candidates.isEmpty()) { throw new BeanCreationException(beanName, "Invalid autowire-marked constructors: " + candidates + ". Found constructor with 'required' Autowired annotation: " + candidate); } requiredConstructor = candidate; } candidates.add(candidate); } else if (candidate.getParameterCount() == 0) { defaultConstructor = candidate; } } if (!candidates.isEmpty()) { // Add default constructor to list of optional constructors, as fallback. if (requiredConstructor == null) { if (defaultConstructor != null) { candidates.add(defaultConstructor); } else if (candidates.size() == 1 && logger.isWarnEnabled()) { logger.warn("Inconsistent constructor declaration on bean with name '" + beanName + "': single autowire-marked constructor flagged as optional - " + "this constructor is effectively required since there is no " + "default constructor to fall back to: " + candidates.get(0)); } } candidateConstructors = candidates.toArray(new Constructor<?>[candidates.size()]); } else if (rawCandidates.length == 1 && rawCandidates[0].getParameterCount() > 0) { candidateConstructors = new Constructor<?>[] { rawCandidates[0] }; } else if (nonSyntheticConstructors == 2 && primaryConstructor != null && defaultConstructor != null && !primaryConstructor.equals(defaultConstructor)) { candidateConstructors = new Constructor<?>[] { primaryConstructor, defaultConstructor }; } else if (nonSyntheticConstructors == 1 && primaryConstructor != null) { candidateConstructors = new Constructor<?>[] { primaryConstructor }; } else { candidateConstructors = new Constructor<?>[0]; } this.candidateConstructorsCache.put(beanClass, candidateConstructors); } } } return (candidateConstructors.length > 0 ? candidateConstructors : null); }
From source file:org.freebxml.omar.server.persistence.rdb.SQLPersistenceManagerImpl.java
/** * Given a Binding object returns the OMARDAO for that object. * */// w w w .j a v a 2s . c om private OMARDAO getDAOForObject(RegistryObjectType ro, ServerRequestContext context) throws RegistryException { OMARDAO dao = null; try { String bindingClassName = ro.getClass().getName(); String daoClassName = bindingClassName.substring(bindingClassName.lastIndexOf('.') + 1, bindingClassName.length() - 4); //Construct the corresonding DAO instance using reflections Class daoClazz = Class.forName("org.freebxml.omar.server.persistence.rdb." + daoClassName + "DAO"); Class[] conParameterTypes = new Class[1]; conParameterTypes[0] = context.getClass(); Object[] conParameterValues = new Object[1]; conParameterValues[0] = context; Constructor[] cons = daoClazz.getDeclaredConstructors(); //Find the constructor that takes RequestContext as its only arg Constructor con = null; for (int i = 0; i < cons.length; i++) { con = cons[i]; if ((con.getParameterTypes().length == 1) && (con.getParameterTypes()[0] == conParameterTypes[0])) { dao = (OMARDAO) con.newInstance(conParameterValues); break; } } } catch (Exception e) { throw new RegistryException(e); } return dao; }
From source file:it.cnr.icar.eric.server.persistence.rdb.SQLPersistenceManagerImpl.java
/** * Given a Binding object returns the OMARDAO for that object. * /*w w w .ja va 2 s. c om*/ */ private OMARDAO getDAOForObject(RegistryObjectType ro, ServerRequestContext context) throws RegistryException { OMARDAO dao = null; try { @SuppressWarnings("unused") String bindingClassName = ro.getClass().getName(); // reuse same mapper as for tablenames // this handles Type1 endings correctly String daoClassName = Utility.getInstance().mapDAOName(ro); // Construct the corresponding DAO instance using reflections Class<?> daoClazz = Class.forName("it.cnr.icar.eric.server.persistence.rdb." + daoClassName + "DAO"); Class<?>[] conParameterTypes = new Class[1]; conParameterTypes[0] = context.getClass(); Object[] conParameterValues = new Object[1]; conParameterValues[0] = context; Constructor<?>[] cons = daoClazz.getDeclaredConstructors(); // Find the constructor that takes RequestContext as its only arg Constructor<?> con = null; for (int i = 0; i < cons.length; i++) { con = cons[i]; if ((con.getParameterTypes().length == 1) && (con.getParameterTypes()[0] == conParameterTypes[0])) { dao = (OMARDAO) con.newInstance(conParameterValues); break; } } } catch (Exception e) { throw new RegistryException(e); } return dao; }
From source file:com.github.wshackle.java4cpp.J4CppMain.java
private static boolean isConstructorToMakeEasy(Constructor c, Class relClss) { Class<?> types[] = c.getParameterTypes(); for (int i = 0; i < types.length; i++) { Class<?> type = types[i]; if (type.isArray() && !type.getComponentType().isPrimitive()) { return false; }/*ww w . ja v a2s . c o m*/ } for (int i = 0; i < types.length; i++) { Class<?> type = types[i]; if (type.isArray() || isString(type)) { return true; } } return false; // return Arrays.stream(c.getParameterTypes()) // .anyMatch(t -> t.isArray() || isString(t)) // && Arrays.stream(c.getParameterTypes()) // .noneMatch(t -> t.isArray() && !t.getComponentType().isPrimitive()); }