List of usage examples for java.lang.reflect Constructor getParameterTypes
@Override
public Class<?>[] getParameterTypes()
From source file:alice.tuprolog.lib.OOLibrary.java
private static boolean moreSpecific(Constructor<?> c1, Constructor<?> c2) { Class<?>[] p1 = c1.getParameterTypes(); Class<?>[] p2 = c2.getParameterTypes(); int n = p1.length; for (int i = 0; i != n; i++) { if (!matchClass(p2[i], p1[i])) { return false; }/*w w w . ja va 2s .c o m*/ } return true; }
From source file:org.obsidian.test.TestAbstract.java
public <T> String buildConstructionStringFromType(Class<T> type, Constructor[] visitedConstructors) { //initialize construction String String constructionString;// w w w. ja v a2s. c om //append equality method types appendEqualityMethodTypes(type); //append the type to the getterTest's dynamic imports appendDynamicImports(type); //if class is abstract, replace with concrete substitution if (Modifier.isAbstract(type.getModifiers()) || type.isInterface()) { type = Helpers.getConcreteSubstitution(type); } //type's simple name String name = type.getSimpleName(); //append the type to the getterTest's dynamic imports appendDynamicImports(type); if (Helpers.PRIMITIVE_CONSTRUCTIONS.get(name) != null) { //get construction from PRIMITIVE_CONSTRUCTIONS constructionString = Helpers.PRIMITIVE_CONSTRUCTIONS.get(name); } else if (type.isArray()) { int numberOfDimensions = StringUtils.countMatches(name, "[]"); constructionString = name.replace("[]", ""); for (int i = 0; i < numberOfDimensions; i++) { constructionString = constructionString + "[0]"; } constructionString = "new " + constructionString; } else if (Modifier.isAbstract(type.getModifiers()) || type.isInterface()) { constructionString = "null"; } else if (type.getConstructors().length == 0) { constructionString = "null"; } else { //not visited constructors ArrayList<Constructor> NVC = Helpers.notVisitedConstructors(type.getConstructors(), visitedConstructors); Constructor constructor = Helpers.getConstructorWithLeastParametersFromList(NVC); if (NVC.isEmpty()) { constructionString = "null"; } else if (constructor.getExceptionTypes().length > 0) { constructionString = "null"; } else { visitedConstructors = Helpers.addConstructor(visitedConstructors, constructor); constructionString = "new " + name + "("; Class[] parameters = constructor.getParameterTypes(); for (int i = 0; i < parameters.length; i++) { constructionString = constructionString + buildConstructionStringFromType(parameters[i], visitedConstructors) + ","; } if (parameters.length != 0) { constructionString = constructionString.substring(0, constructionString.length() - 1); } constructionString = constructionString + ")"; } } //this will prevent ambiguity in constructors with parmeter that //cannot be constructed if (constructionString.contains("null")) { constructionString = "null"; } return constructionString; }
From source file:org.openehr.validation.DataValidatorImpl.java
/** * Retorna construtor de um parametro {@link String} * @param klass// w ww .j ava 2 s . co m * @return * @throws SecurityException */ private Constructor getConstructorWithStringArgument(Class klass) { Constructor constructor = null; for (Constructor constr : klass.getConstructors()) { if (constr.getParameterTypes().length == 1 && constr.getParameterTypes()[0].equals(String.class)) { constructor = constr; break; } } return constructor; }
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); }/*from w w w .ja v a 2 s . com*/ 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.forgerock.openidm.selfservice.impl.SelfService.java
private ProgressStageProvider newProgressStageProvider(final Client httpClient) { return new ProgressStageProvider() { @Override//from ww w. j ava 2 s . c o m public ProgressStage<StageConfig> get(Class<? extends ProgressStage<StageConfig>> progressStageClass) { Constructor<?>[] constructors = progressStageClass.getConstructors(); if (constructors.length > 1) { throw new StageConfigException( "Only expected one constructor for the configured progress stage " + progressStageClass); } try { Constructor<? extends ProgressStage<StageConfig>> constructor = progressStageClass .getConstructor(constructors[0].getParameterTypes()); Object[] parameters = getParameters(constructor); return constructor.newInstance(parameters); } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException | InstantiationException e) { throw new StageConfigException("Unable to instantiate the configured progress stage", e); } } private Object[] getParameters(Constructor<?> constructor) { Class<?>[] parameterTypes = constructor.getParameterTypes(); Object[] parameters = new Object[parameterTypes.length]; for (int i = 0; i < parameterTypes.length; i++) { if (parameterTypes[i].equals(ConnectionFactory.class)) { parameters[i] = connectionFactory; } else if (parameterTypes[i].equals(Client.class)) { parameters[i] = httpClient; } else { throw new StageConfigException( "Unexpected parameter type for configured progress stage " + parameters[i]); } } return parameters; } }; }
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 w ww . ja va2 s. 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:org.mwc.debrief.editable.test.EditableTests.java
private Editable getEditable(IType type) { Editable editable = null;/*from w w w. j av a 2 s . c o m*/ switch (type.getFullyQualifiedName()) { case "Debrief.Wrappers.SensorWrapper": SensorWrapper sensor = new SensorWrapper("tester"); final java.util.Calendar cal = new java.util.GregorianCalendar(2001, 10, 4, 4, 4, 0); // and create the list of sensor contact data items cal.set(2001, 10, 4, 4, 4, 0); sensor.add(new SensorContactWrapper("tester", new HiResDate(cal.getTime().getTime()), null, null, null, null, null, 1, sensor.getName())); cal.set(2001, 10, 4, 4, 4, 23); sensor.add(new SensorContactWrapper("tester", new HiResDate(cal.getTime().getTime()), null, null, null, null, null, 1, sensor.getName())); editable = sensor; break; case "MWC.GUI.Shapes.ChartFolio": editable = new ChartFolio(false, Color.white); break; case "org.mwc.cmap.naturalearth.wrapper.NELayer": editable = new NELayer(Activator.getDefault().getDefaultStyleSet()); break; case "MWC.GUI.VPF.CoverageLayer$ReferenceCoverageLayer": final LibrarySelectionTable LST = null; final DebriefFeatureWarehouse myWarehouse = new DebriefFeatureWarehouse(); final FeaturePainter fp = new FeaturePainter("libref", "Coastline"); fp.setVisible(true); editable = new CoverageLayer.ReferenceCoverageLayer(LST, myWarehouse, "libref", "libref", "Coastline", fp); break; case "MWC.GUI.Chart.Painters.ETOPOPainter": editable = new ETOPOPainter("etopo", null); break; case "MWC.GUI.ETOPO.ETOPO_2_Minute": editable = new ETOPO_2_Minute("etopo"); break; case "MWC.GUI.ExternallyManagedDataLayer": editable = new ExternallyManagedDataLayer("test", "test", "test"); break; case "MWC.GUI.Shapes.CircleShape": editable = new CircleShape(new WorldLocation(2d, 2d, 2d), 2d); break; case "Debrief.Wrappers.Track.SplittableLayer": editable = new SplittableLayer(true); break; case "org.mwc.debrief.satc_interface.data.SATC_Solution": final ISolversManager solvMgr = SATC_Activator.getDefault().getService(ISolversManager.class, true); final ISolver newSolution = solvMgr.createSolver("test"); editable = new SATC_Solution(newSolution); break; case "MWC.GUI.Shapes.PolygonShape": editable = new PolygonShape(null); break; case "ASSET.GUI.Painters.NoiseSourcePainter": editable = new ASSET.GUI.Painters.NoiseSourcePainter.PainterTest().getEditable(); break; case "ASSET.GUI.Painters.ScenarioNoiseLevelPainter": editable = new ASSET.GUI.Painters.ScenarioNoiseLevelPainter.NoiseLevelTest().getEditable(); break; case "ASSET.GUI.Workbench.Plotters.ScenarioParticipantWrapper": editable = new ScenarioParticipantWrapper(new SSN(12), null); break; case "Debrief.Wrappers.PolygonWrapper": // get centre of area WorldLocation centre = new WorldLocation(12, 12, 12); // create the shape, based on the centre final Vector<PolygonNode> path2 = new Vector<PolygonNode>(); final PolygonShape newShape = new PolygonShape(path2); // and now wrap the shape final PolygonWrapper theWrapper = new PolygonWrapper("New Polygon", newShape, PlainShape.DEFAULT_COLOR, null); // store the new point newShape.add(new PolygonNode("1", centre, (PolygonShape) theWrapper.getShape())); editable = theWrapper; break; case "Debrief.Wrappers.Track.AbsoluteTMASegment": WorldSpeed speed = new WorldSpeed(5, WorldSpeed.Kts); double course = 33; WorldLocation origin = new WorldLocation(12, 12, 12); HiResDate startTime = new HiResDate(11 * 60 * 1000); HiResDate endTime = new HiResDate(17 * 60 * 1000); editable = new AbsoluteTMASegment(course, speed, origin, startTime, endTime); break; case "Debrief.Wrappers.Track.RelativeTMASegment": speed = new WorldSpeed(5, WorldSpeed.Kts); course = 33; final WorldVector offset = new WorldVector(12, 12, 0); editable = new RelativeTMASegment(course, speed, offset, null); break; case "Debrief.Wrappers.Track.PlanningSegment": speed = new WorldSpeed(5, WorldSpeed.Kts); course = 33; final WorldDistance worldDistance = new WorldDistance(5, WorldDistance.MINUTES); editable = new PlanningSegment("test", course, speed, worldDistance, Color.WHITE); break; case "org.mwc.debrief.satc_interface.data.wrappers.BMC_Wrapper": BearingMeasurementContribution bmc = new BearingMeasurementContribution(); bmc.setName("Measured bearing"); bmc.setAutoDetect(false); editable = new BMC_Wrapper(bmc); break; case "org.mwc.debrief.satc_interface.data.wrappers.FMC_Wrapper": FrequencyMeasurementContribution fmc = new FrequencyMeasurementContribution(); fmc.setName("Measured frequence"); editable = new FMC_Wrapper(fmc); break; case "Debrief.Wrappers.SensorContactWrapper": origin = new WorldLocation(0, 0, 0); editable = new SensorContactWrapper("blank track", new HiResDate(new java.util.Date().getTime()), new WorldDistance(1, WorldDistance.DEGS), 55d, origin, java.awt.Color.red, "my label", 1, "theSensorName"); break; case "Debrief.Wrappers.FixWrapper": final Fix fx = new Fix(new HiResDate(12, 0), new WorldLocation(2d, 2d, 2d), 2d, 2d); final TrackWrapper tw = new TrackWrapper(); tw.setName("here ew arw"); FixWrapper ed = new FixWrapper(fx); ed.setTrackWrapper(tw); editable = ed; break; case "Debrief.Wrappers.ShapeWrapper": centre = new WorldLocation(2d, 2d, 2d); editable = new ShapeWrapper("new ellipse", new EllipseShape(centre, 0, new WorldDistance(0, WorldDistance.DEGS), new WorldDistance(0, WorldDistance.DEGS)), java.awt.Color.red, null); break; case "Debrief.GUI.Tote.Painters.PainterManager": final StepControl stepper = new Debrief.GUI.Tote.Swing.SwingStepControl(null, null, null, null, null, null); editable = new PainterManager(stepper); break; case "Debrief.Wrappers.TMAContactWrapper": origin = new WorldLocation(2, 2, 0); final HiResDate theDTG = new HiResDate(new java.util.Date().getTime()); final EllipseShape theEllipse = new EllipseShape(origin, 45, new WorldDistance(10, WorldDistance.DEGS), new WorldDistance(5, WorldDistance.DEGS)); theEllipse.setName("test ellipse"); editable = new TMAContactWrapper("blank sensor", "blank track", theDTG, origin, 5d, 6d, 1d, Color.pink, "my label", theEllipse, "some symbol"); break; case "MWC.GUI.JFreeChart.NewFormattedJFreeChart": XYPlot plot = new XYPlot(); DefaultXYItemRenderer renderer = new DefaultXYItemRenderer(); plot.setRenderer(renderer); editable = new NewFormattedJFreeChart("test", new java.awt.Font("Dialog", 0, 18), plot, false); break; case "org.mwc.cmap.core.ui_support.swt.SWTCanvasAdapter": final Editable[] edit = new Editable[1]; Display.getDefault().syncExec(new Runnable() { @Override public void run() { edit[0] = new SWTCanvasAdapter(null); } }); editable = edit[0]; break; case "ASSET.Models.Decision.Conditions.OrCondition": System.out.println(type.getFullyQualifiedName() + " hasn't public constructor."); return null; case "ASSET.Models.Decision.Movement.RectangleWander": final WorldLocation topLeft = SupportTesting.createLocation(0, 10000); final WorldLocation bottomRight = SupportTesting.createLocation(10000, 0); final WorldArea theArea = new WorldArea(topLeft, bottomRight); editable = new RectangleWander(theArea, "rect wander"); break; case "org.mwc.debrief.satc_interface.data.wrappers.BMC_Wrapper$BearingMeasurementWrapper": bmc = new BearingMeasurementContribution(); bmc.setName("Measured bearing"); bmc.setAutoDetect(false); CoreMeasurement cm = new CoreMeasurement(new Date()); BMC_Wrapper bmcw = new BMC_Wrapper(bmc); editable = bmcw.new BearingMeasurementWrapper(cm); break; case "org.mwc.debrief.satc_interface.data.wrappers.FMC_Wrapper$FrequencyMeasurementEditable": fmc = new FrequencyMeasurementContribution(); fmc.setName("Measured frequence"); FMC_Wrapper fmcw = new FMC_Wrapper(fmc); cm = new CoreMeasurement(new Date()); editable = fmcw.new FrequencyMeasurementEditable(cm); break; case "ASSET.GUI.SuperSearch.Plotters.SSGuiSupport$ParticipantListener": SSGuiSupport ssgs = new SSGuiSupport(); ssgs.setScenario(new MultiForceScenario()); editable = new SSGuiSupport.ParticipantListener(new CoreParticipant(12), ssgs); break; case "ASSET.GUI.Workbench.Plotters.BasePlottable": // skip it return null; case "MWC.TacticalData.GND.GTrack": // skip it return null; default: break; } if (editable != null) { return editable; } Class<?> clazz; try { clazz = Class.forName(type.getFullyQualifiedName()); } catch (ClassNotFoundException e1) { //e1.printStackTrace(); System.out.println("CNFE " + e1.getMessage() + " " + type.getFullyQualifiedName()); return null; } try { @SuppressWarnings("unused") Method infoMethod = clazz.getDeclaredMethod("getInfo", new Class[0]); } catch (Exception e) { return null; } try { editable = (Editable) clazz.newInstance(); } catch (Exception e) { Constructor<?>[] constructors = clazz.getConstructors(); for (Constructor<?> constructor : constructors) { try { Class<?>[] paramTypes = constructor.getParameterTypes(); Object[] params = new Object[paramTypes.length]; for (int i = 0; i < paramTypes.length; i++) { Class<?> paramType = paramTypes[i]; if (HiResDate.class.equals(paramType)) { params[i] = new HiResDate(new Date()); } else if (WorldDistance.class.equals(paramType)) { params[i] = new WorldDistance(12d, WorldDistance.DEGS); } else if (WorldSpeed.class.equals(paramType)) { params[i] = new WorldSpeed(12, WorldSpeed.M_sec); } else if (WorldLocation.class.equals(paramType)) { params[i] = new WorldLocation(12, 12, 12); } else if ("java.lang.String".equals(paramType.getName())) { params[i] = "test"; } else if (!paramType.isPrimitive()) { params[i] = null; } else { if (paramType.equals(int.class)) { params[i] = new Integer("0"); } if (paramType.equals(boolean.class)) { params[i] = Boolean.FALSE; } if (paramType.equals(long.class)) { params[i] = new Long("0"); } if (paramType.equals(double.class)) { params[i] = new Double("0"); } if (paramType.equals(float.class)) { params[i] = new Float("0"); } if (paramType.equals(short.class)) { params[i] = new Short("0"); } } } editable = (Editable) constructor.newInstance(params); break; } catch (Exception e1) { // ignore //System.out.println(e1.getMessage()); //e1.printStackTrace(); } } } if (editable == null) { System.out.println("Can't instantiate type " + type.getFullyQualifiedName()); } return editable; }
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 www . j a va 2 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.openehr.build.RMObjectBuilder.java
/** * Finds the matching RM class that can be used to create RM object for * given value map//from w ww .j av a 2 s . co m * * @param valueMap * @return null if no match RM class is found */ public String findMatchingRMClass(Map<String, Object> valueMap) { List simpleTypes = Arrays.asList(SKIPPED_TYPES_IN_MATCHING); for (Class rmClass : typeMap.values()) { log.debug("matching rmClass: " + rmClass.getName()); if (simpleTypes.contains(rmClass.getSimpleName())) { continue; // skip simple value types } // replace underscore separated names with camel case Map<String, Object> filteredMap = new HashMap<String, Object>(); for (String name : valueMap.keySet()) { filteredMap.put(toCamelCase(name), valueMap.get(name)); } Constructor constructor = fullConstructor(rmClass); if (constructor == null) { throw new RuntimeException("annotated constructor missing for " + rmClass); } Annotation[][] annotations = constructor.getParameterAnnotations(); if (annotations == null || annotations.length == 0) { throw new RuntimeException("attribute annotations missing for " + rmClass); } Class[] types = constructor.getParameterTypes(); boolean matched = true; Set<String> attributes = new HashSet<String>(); for (int i = 0; i < types.length; i++) { if (annotations[i].length == 0) { throw new RuntimeException("attribute annotation missing for" + rmClass); } Attribute attribute = (Attribute) annotations[i][0]; attributes.add(attribute.name()); log.debug("checking attribute: " + attribute.name()); String attrName = attribute.name(); Object attrValue = filteredMap.get(attrName); if (attribute.required() && attrValue == null) { log.debug("missing required attribute.."); matched = false; break; } else if (attrValue != null) { if (((attrValue instanceof Boolean) && types[i] != boolean.class) || ((attrValue instanceof Integer) && types[i] != Integer.class) || ((attrValue instanceof Double) && types[i] != double.class)) { log.debug("wrong primitive value type for attribute.."); matched = false; break; } else if (!types[i].isPrimitive() && !types[i].isInstance(attrValue)) { log.debug("wrong value type for attribute.."); matched = false; break; } } } for (String attr : filteredMap.keySet()) { if (!attributes.contains(attr)) { log.debug("unknown attribute: " + attr); matched = false; } } // matching found if (matched) { String className = rmClass.getSimpleName(); log.debug(">>> MATCHING FOUND: " + className); return className; } } return null; }
From source file:org.springframework.web.method.annotation.ModelAttributeMethodProcessor.java
/** * Construct a new attribute instance with the given constructor. * <p>Called from/*www. j a v a 2 s . c o m*/ * {@link #createAttribute(String, MethodParameter, WebDataBinderFactory, NativeWebRequest)} * after constructor resolution. * @param ctor the constructor to use * @param attributeName the name of the attribute (never {@code null}) * @param binderFactory for creating WebDataBinder instance * @param webRequest the current request * @return the created model attribute (never {@code null}) * @throws BindException in case of constructor argument binding failure * @throws Exception in case of constructor invocation failure * @since 5.0 */ protected Object constructAttribute(Constructor<?> ctor, String attributeName, WebDataBinderFactory binderFactory, NativeWebRequest webRequest) throws Exception { if (ctor.getParameterCount() == 0) { // A single default constructor -> clearly a standard JavaBeans arrangement. return BeanUtils.instantiateClass(ctor); } // A single data class constructor -> resolve constructor arguments from request parameters. ConstructorProperties cp = ctor.getAnnotation(ConstructorProperties.class); String[] paramNames = (cp != null ? cp.value() : parameterNameDiscoverer.getParameterNames(ctor)); Assert.state(paramNames != null, () -> "Cannot resolve parameter names for constructor " + ctor); Class<?>[] paramTypes = ctor.getParameterTypes(); Assert.state(paramNames.length == paramTypes.length, () -> "Invalid number of parameter names: " + paramNames.length + " for constructor " + ctor); Object[] args = new Object[paramTypes.length]; WebDataBinder binder = binderFactory.createBinder(webRequest, null, attributeName); String fieldDefaultPrefix = binder.getFieldDefaultPrefix(); String fieldMarkerPrefix = binder.getFieldMarkerPrefix(); boolean bindingFailure = false; for (int i = 0; i < paramNames.length; i++) { String paramName = paramNames[i]; Class<?> paramType = paramTypes[i]; Object value = webRequest.getParameterValues(paramName); if (value == null) { if (fieldDefaultPrefix != null) { value = webRequest.getParameter(fieldDefaultPrefix + paramName); } if (value == null && fieldMarkerPrefix != null) { if (webRequest.getParameter(fieldMarkerPrefix + paramName) != null) { value = binder.getEmptyValue(paramType); } } } try { MethodParameter methodParam = new MethodParameter(ctor, i); if (value == null && methodParam.isOptional()) { args[i] = (methodParam.getParameterType() == Optional.class ? Optional.empty() : null); } else { args[i] = binder.convertIfNecessary(value, paramType, methodParam); } } catch (TypeMismatchException ex) { ex.initPropertyName(paramName); binder.getBindingErrorProcessor().processPropertyAccessException(ex, binder.getBindingResult()); bindingFailure = true; args[i] = value; } } if (bindingFailure) { if (binder.getBindingResult() instanceof AbstractBindingResult) { AbstractBindingResult result = (AbstractBindingResult) binder.getBindingResult(); for (int i = 0; i < paramNames.length; i++) { result.recordFieldValue(paramNames[i], paramTypes[i], args[i]); } } throw new BindException(binder.getBindingResult()); } return BeanUtils.instantiateClass(ctor, args); }