List of usage examples for java.lang.reflect Constructor getParameterTypes
@Override
public Class<?>[] getParameterTypes()
From source file:org.kepler.objectmanager.repository.RepositoryManager.java
/** * creates and instance of a repository/* w ww . ja v a 2 s .c om*/ * *@param newClass *@param arguments *@return Repository */ private Repository createInstance(Class newClass, Object[] arguments) throws Exception { 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 (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) { Repository newRepository = (Repository) constructor.newInstance(arguments); return newRepository; } } // 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:net.abhinavsarkar.spelhelper.SpelHelper.java
/** * Registers the public constructors of the class `clazz` so that they * can be called by their simple name from SpEL expressions. * @param clazz The class to register the constructors from. * @return The current instance of SpelHelper. This is for chaining * the methods calls./*w ww . j ava2 s . c om*/ */ public SpelHelper registerConstructorsFromClass(final Class<?> clazz) { for (Constructor<?> constructor : asList(clazz.getConstructors())) { registeredConstructors.put(constructor.getDeclaringClass().getSimpleName() + Arrays.toString(constructor.getParameterTypes()), constructor); } return this; }
From source file:com.sabdroidex.utils.json.impl.SimpleJSONMarshaller.java
/** * This method creates an instance of the object targeted by the Class passed to the constructor, * it then tries to call all the methods with the JSONSetter annotation with the corresponding field. * /*from ww w . j a v a 2 s . com*/ * @param jsonObject * This is the JSON object that will be used to fill-up an * instance of the Class that is targeted. * @return * @throws ClassNotFoundException * @throws InstantiationException * @throws IllegalAccessException */ @SuppressWarnings("unchecked") public Object unMarshal(final JSONObject jsonObject) throws InstantiationException, IllegalAccessException { Object result = clazz.newInstance(); try { Method[] methods = clazz.getMethods(); for (int i = 0; i < methods.length; i++) { JSONSetter setter = methods[i].getAnnotation(JSONSetter.class); /** * Checking if the method has the JSONSetter annotation This * only allows one parameter per setter method */ if (setter != null) { /** * Checking the JSONType defined in the annotation */ if (setter.type() == JSONType.SIMPLE) { /** * Used for simple object (String, Integer, etc ...) */ try { Object parameter = jsonObject.get(setter.name()); methods[i].invoke(result, parameter); } catch (JSONException exception) { if (Debug.isDebuggerConnected()) { Log.d(TAG, methods[i].getName() + " " + exception.getLocalizedMessage()); } } catch (IllegalArgumentException exception) { /** * This happens if the object returned by the getter * is a null, it would be defined as a JSONObject * and thus cause an IllegalArgumentException when * calling the targeted method. * * This is yet another problem in an Android API * which is bypassed by creating an empty object of * the awaited type. */ if (Debug.isDebuggerConnected()) { Log.w(TAG, methods[i].getName() + " " + exception.getLocalizedMessage()); } try { Constructor<?>[] constructors = methods[i].getParameterTypes()[0].getConstructors(); Object parameter = null; /** * Checking all the constructor of the parameter * object. */ for (Constructor<?> constructor : constructors) { Class<?>[] params = constructor.getParameterTypes(); if (params.length == 0) { /** * If the empty constructor is found we * use it. */ parameter = constructor.newInstance(); break; } else if (params[0].isPrimitive()) { /** * If a constructor using a primitive is * found we use it, this happens for * classes that extend Number. */ parameter = constructor.newInstance(0); } } methods[i].invoke(result, parameter); } catch (Exception e) { if (Debug.isDebuggerConnected()) { Log.d(TAG, methods[i].getName() + " " + e.getLocalizedMessage()); } } } } else if (setter.type() == JSONType.JSON_OBJECT) { /** * Used for object that are instantiated from JSON * (Show, Movie, etc ...) */ try { SimpleJSONMarshaller simpleJSONMarshaller = new SimpleJSONMarshaller( methods[i].getParameterTypes()[0]); JSONObject jsonElement = jsonObject.getJSONObject(setter.name()); Object parameter = simpleJSONMarshaller.unMarshal(jsonElement); methods[i].invoke(result, parameter); } catch (JSONException exception) { if (Debug.isDebuggerConnected()) { Log.d(TAG, methods[i].getName() + " " + exception.getLocalizedMessage()); } try { Constructor<?>[] constructors = methods[i].getParameterTypes()[0].getConstructors(); Object parameter = null; /** * Checking all the constructor of the parameter * object. */ for (Constructor<?> constructor : constructors) { Class<?>[] params = constructor.getParameterTypes(); if (params.length == 0) { /** * If the empty constructor is found we * use it. */ parameter = constructor.newInstance(); break; } else if (params[0].isPrimitive()) { /** * If a constructor using a primitive is * found we use it, this happens for * classes that extend Number. */ parameter = constructor.newInstance(0); } } methods[i].invoke(result, parameter); } catch (Exception e) { if (Debug.isDebuggerConnected()) { Log.d(TAG, methods[i].getName() + " " + e.getLocalizedMessage()); } } } } else if (setter.type() == JSONType.LIST) { /** * Used for object that represent a Collection (List, * ArrayList, Vector, etc ...) */ try { JSONArray jsonArray = jsonObject.getJSONArray(setter.name()); Collection<Object> collection = null; if (methods[i].getParameterTypes()[0] == List.class) { collection = (Collection<Object>) setter.listClazz().newInstance(); } else { collection = (Collection<Object>) methods[i].getParameterTypes()[0].newInstance(); } for (int j = 0; j < jsonArray.length(); j++) { Object element = jsonArray.get(j); if (setter.objectClazz() != Void.class) { SimpleJSONMarshaller simpleJSONMarshaller = new SimpleJSONMarshaller( setter.objectClazz()); element = simpleJSONMarshaller.unMarshal((JSONObject) element); } collection.add(element); } methods[i].invoke(result, collection); } catch (JSONException exception) { if (Debug.isDebuggerConnected()) { Log.d(TAG, methods[i].getName() + " " + exception.getLocalizedMessage()); } } } else if (setter.type() == JSONType.UNKNOWN_KEY_ELEMENTS) { /** * Used for object that represent a Collection (List, * ArrayList, Vector, etc ...) and that do not have a * key that is predefined. */ try { Collection<Object> collection = null; if (methods[i].getParameterTypes()[0] == List.class) { collection = (Collection<Object>) setter.listClazz().newInstance(); } else { collection = (Collection<Object>) methods[i].getParameterTypes()[0].newInstance(); } Iterator<?> iterator = jsonObject.keys(); while (iterator.hasNext()) { String key = (String) iterator.next(); Object element = jsonObject.get(key); if (setter.objectClazz() != Void.class) { SimpleJSONMarshaller simpleJSONMarshaller = new SimpleJSONMarshaller( setter.objectClazz()); element = simpleJSONMarshaller.unMarshal((JSONObject) element); if (element instanceof UnknowMappingElement) { ((UnknowMappingElement) element).setId(key); } } collection.add(element); } methods[i].invoke(result, collection); } catch (JSONException exception) { if (Debug.isDebuggerConnected()) { Log.d(TAG, methods[i].getName() + " " + exception.getLocalizedMessage()); } } } } } } catch (Exception e) { if (Debug.isDebuggerConnected()) { Log.d(TAG, e.getLocalizedMessage()); } } return result; }
From source file:org.fit.cssbox.scriptbox.script.javascript.java.HostedJavaObject.java
@Override public Scriptable construct(Context cx, Scriptable scope, Object[] args) { Scriptable result = new NativeObject(); result.setParentScope(getParentScope()); Set<ClassConstructor> constructors = objectMembers.getConstructors(); if (constructors == null || constructors.isEmpty()) { throw new ObjectException("Object does not contain any constructors!"); }/*from w w w .j a v a2 s . c o m*/ InvocableMember<?> nearestInvocable = HostedJavaMethod.getNearestObjectFunction(args, constructors); if (nearestInvocable == null) { throw new FunctionException("Unable to match nearest constructor"); } ConstructorMember nearestConstructorMember = (ConstructorMember) nearestInvocable; Constructor<?> constructor = nearestConstructorMember.getMember(); Class<?> expectedTypes[] = constructor.getParameterTypes(); Object[] castedArgs = HostedJavaMethod.castArgs(expectedTypes, args); try { Object newInstance = constructor.newInstance(castedArgs); newInstance = wrapObject(newInstance); if (newInstance instanceof Scriptable) { result = (Scriptable) newInstance; } } catch (Exception e) { throw new UnknownException(e); } return result; }
From source file:tiemens.util.instancer.antlr.InstancerCode.java
/** * Loop through the constructors, find the best possible. *///w w w . ja v a2 s. c o m private Constructor<?> getConstructorBySelecting(Class<?> dclz, Class<?>[] parameterTypes) throws NoSuchMethodException { Constructor<?> ret = null; for (Constructor<?> candidate : dclz.getConstructors()) { Class<?>[] types = candidate.getParameterTypes(); boolean success = false; logger.fine(".Checking constructor for " + dclz.getName() + " [types=" + types + "]" + " : " + Arrays.toString(types)); if ((types == null) || (types.length == 0)) { logger.fine("--Special case void"); if ((parameterTypes == null) || (parameterTypes.length == 0)) { success = true; } } else if (parameterTypes == null) { success = false; } else if (types.length == parameterTypes.length) { success = true; for (int i = 0, n = types.length; i < n; i++) { if (!correctIsAssignableFrom(types[i], parameterTypes[i])) { success = false; } } } if (success) { logger.fine("..success"); ret = candidate; break; } else { logger.fine("..failed"); } } return ret; }
From source file:org.jolokia.converter.object.StringToObjectConverter.java
private Object convertByConstructor(String pType, String pValue) { Class<?> expectedClass = ClassUtil.classForName(pType); if (expectedClass != null) { for (Constructor<?> constructor : expectedClass.getConstructors()) { // only support only 1 constructor parameter if (constructor.getParameterTypes().length == 1 && constructor.getParameterTypes()[0].isAssignableFrom(String.class)) { try { return constructor.newInstance(pValue); } catch (Exception ignore) { }/*w w w. j ava 2s . com*/ } } } return null; }
From source file:com.jsen.javascript.java.HostedJavaObject.java
@Override public Scriptable construct(Context cx, Scriptable scope, Object[] args) { Scriptable result = new NativeObject(); result.setParentScope(getParentScope()); Set<ClassConstructor> constructors = objectMembers.getConstructors(); if (constructors == null || constructors.isEmpty()) { throw new ObjectException("Object does not contain any constructors!"); }/*from ww w . j a va2 s. co m*/ InvocableMember<?> nearestInvocable = HostedJavaMethod.getNearestObjectFunction(args, constructors); if (nearestInvocable == null) { throw new FunctionException("Unable to match nearest constructor"); } ConstructorMember nearestConstructorMember = (ConstructorMember) nearestInvocable; Constructor<?> constructor = nearestConstructorMember.getMember(); Class<?> expectedTypes[] = constructor.getParameterTypes(); Object[] castedArgs = HostedJavaMethod.castArgs(expectedTypes, args); try { Object newInstance = constructor.newInstance(castedArgs); newInstance = wrapObject(newInstance); if (newInstance instanceof Scriptable) { result = (Scriptable) newInstance; } } catch (Exception e) { throw new UnknownException("Unable to construct object " + nearestConstructorMember.getName(), e); } return result; }
From source file:org.apache.sling.ide.eclipse.m2e.EmbeddedArchetypeInstaller.java
private MavenSession reflectiveCreateMavenSession(PlexusContainer container, DefaultMaven mvn, MavenExecutionRequest request)// ww w .j a va2 s . c o m throws IllegalAccessException, InvocationTargetException, InstantiationException { Method newRepoSessionMethod = null; for (Method m : mvn.getClass().getMethods()) { if ("newRepositorySession".equals(m.getName())) { newRepoSessionMethod = m; break; } } if (newRepoSessionMethod == null) { throw new IllegalArgumentException("No 'newRepositorySession' method found on object " + mvn + " of type " + mvn.getClass().getName()); } Object repositorySession = newRepoSessionMethod.invoke(mvn, request); MavenExecutionResult result = new DefaultMavenExecutionResult(); Constructor<?> constructor = null; outer: for (Constructor<?> c : MavenSession.class.getConstructors()) { for (Class<?> klazz : getClasses(repositorySession)) { Class<?>[] check = new Class<?>[] { PlexusContainer.class, klazz, MavenExecutionRequest.class, MavenExecutionResult.class }; if (Arrays.equals(c.getParameterTypes(), check)) { constructor = c; break outer; } } } if (constructor == null) { throw new IllegalArgumentException("Unable to found matching MavenSession constructor"); } return (MavenSession) constructor.newInstance(container, repositorySession, request, result); }
From source file:br.com.nordestefomento.jrimum.utilix.Field.java
@SuppressWarnings("unchecked") private void readStringOrNumericField(String valueAsString) { Class<?> c = value.getClass(); for (Constructor<?> cons : c.getConstructors()) { if (cons.getParameterTypes().length == 1) { if (cons.getParameterTypes()[0].equals(String.class)) { try { value = (G) cons.newInstance(valueAsString); } catch (IllegalArgumentException e) { getGenericReadError(e, valueAsString).printStackTrace(); } catch (InstantiationException e) { getGenericReadError(e, valueAsString).printStackTrace(); } catch (IllegalAccessException e) { getGenericReadError(e, valueAsString).printStackTrace(); } catch (InvocationTargetException e) { getGenericReadError(e, valueAsString).printStackTrace(); }/*from ww w. j a v a 2s . c o m*/ } } } }
From source file:com.weibo.api.motan.core.extension.ExtensionLoader.java
private void checkConstructorPublic(Class<T> clz) { Constructor<?>[] constructors = clz.getConstructors(); if (constructors == null || constructors.length == 0) { failThrows(clz, "Error has no public no-args constructor"); }//from w w w. ja v a2 s . c o m for (Constructor<?> constructor : constructors) { if (Modifier.isPublic(constructor.getModifiers()) && constructor.getParameterTypes().length == 0) { return; } } failThrows(clz, "Error has no public no-args constructor"); }