List of usage examples for java.lang.reflect Constructor getParameterTypes
@Override
public Class<?>[] getParameterTypes()
From source file:org.eclipse.wb.internal.core.utils.reflect.ReflectionUtils.java
/** * @return signature for given {@link Constructor}. This signature is not same signature as in JVM * or JDT, just some string that unique identifies constructor in its {@link Class}. *//*from ww w .j av a2 s . co m*/ public static String getConstructorSignature(Constructor<?> constructor) { Assert.isNotNull(constructor); return getConstructorSignature(constructor.getParameterTypes()); }
From source file:org.eclipse.wb.internal.core.utils.reflect.ReflectionUtils.java
/** * @return the {@link Constructor} which can be invoked with given arguments, may be * <code>null</code>. *//*from w w w. ja v a 2 s. c o m*/ @SuppressWarnings("unchecked") public static <T> Constructor<T> getConstructorForArguments(Class<T> clazz, Object... arguments) { Assert.isNotNull(clazz); Assert.isNotNull(arguments); for (Constructor<?> constructor : clazz.getConstructors()) { Class<?>[] parameterTypes = constructor.getParameterTypes(); // check compatibility of each parameter and argument boolean canUse = true; if (parameterTypes.length == arguments.length) { for (int i = 0; i < parameterTypes.length; i++) { Class<?> parameterType = parameterTypes[i]; Object argument = arguments[i]; if (!isAssignableFrom(parameterType, argument)) { canUse = false; break; } } // use if possible if (canUse) { return (Constructor<T>) constructor; } } } // no compatible constructor return null; }
From source file:org.devproof.portal.core.module.common.page.TemplatePage.java
private Component createGenericBoxInstance(Class<? extends Component> boxClazz) { for (Constructor<?> constr : boxClazz.getConstructors()) { Class<?> param[] = constr.getParameterTypes(); if (param.length == 2 && param[0] == String.class && param[1] == PageParameters.class) { try { return (Component) constr.newInstance(getBoxId(), params); } catch (Exception e) { throw new UnhandledException(e); }//from www . j av a 2s . c om } else if (param.length == 1 && param[0] == String.class) { try { return (Component) constr.newInstance(getBoxId()); } catch (Exception e) { throw new UnhandledException(e); } } } return null; }
From source file:RevEngAPI.java
/** Generate a .java file for the outline of the given class. */ public void doClass(Class c) throws IOException { className = c.getName();/*from w w w .j a v a 2 s. co m*/ // pre-compute offset for stripping package name classNameOffset = className.lastIndexOf('.') + 1; // Inner class if (className.indexOf('$') != -1) return; // get name, as String, with . changed to / String slashName = className.replace('.', '/'); String fileName = slashName + ".java"; System.out.println(className + " --> " + fileName); String dirName = slashName.substring(0, slashName.lastIndexOf("/")); new File(dirName).mkdirs(); // create the file. PrintWriter out = new PrintWriter(new FileWriter(fileName)); out.println("// Generated by RevEngAPI for class " + className); // If in a package, say so. Package pkg; if ((pkg = c.getPackage()) != null) { out.println("package " + pkg.getName() + ';'); out.println(); } // print class header int cMods = c.getModifiers(); printMods(cMods, out); out.print("class "); out.print(trim(c.getName())); out.print(' '); // XXX get superclass out.println('{'); // print constructors Constructor[] ctors = c.getDeclaredConstructors(); for (int i = 0; i < ctors.length; i++) { if (i == 0) { out.println(); out.println("\t// Constructors"); } Constructor cons = ctors[i]; int mods = cons.getModifiers(); if (Modifier.isPrivate(mods)) continue; out.print('\t'); printMods(mods, out); out.print(trim(cons.getName()) + "("); Class[] classes = cons.getParameterTypes(); for (int j = 0; j < classes.length; j++) { if (j > 0) out.print(", "); out.print(trim(classes[j].getName()) + ' ' + mkName(PREFIX_ARG, j)); } out.println(") {"); out.print("\t}"); } // print method names Method[] mems = c.getDeclaredMethods(); for (int i = 0; i < mems.length; i++) { if (i == 0) { out.println(); out.println("\t// Methods"); } Method m = mems[i]; if (m.getName().startsWith("access$")) continue; int mods = m.getModifiers(); if (Modifier.isPrivate(mods)) continue; out.print('\t'); printMods(mods, out); out.print(m.getReturnType()); out.print(' '); out.print(trim(m.getName()) + "("); Class[] classes = m.getParameterTypes(); for (int j = 0; j < classes.length; j++) { if (j > 0) out.print(", "); out.print(trim(classes[j].getName()) + ' ' + mkName(PREFIX_ARG, j)); } out.println(") {"); out.println("\treturn " + defaultValue(m.getReturnType()) + ';'); out.println("\t}"); } // print fields Field[] flds = c.getDeclaredFields(); for (int i = 0; i < flds.length; i++) { if (i == 0) { out.println(); out.println("\t// Fields"); } Field f = flds[i]; int mods = f.getModifiers(); if (Modifier.isPrivate(mods)) continue; out.print('\t'); printMods(mods, out); out.print(trim(f.getType().getName())); out.print(' '); out.print(f.getName()); if (Modifier.isFinal(mods)) { try { out.print(" = " + f.get(null)); } catch (IllegalAccessException ex) { out.print("; // " + ex.toString()); } } out.println(';'); } out.println("}"); //out.flush(); out.close(); }
From source file:org.nuxeo.ecm.core.io.registry.reflect.MarshallerInspector.java
/** * Introspect this marshaller: gets instantiation mode, supported mimetype, gets the managed class, generic type and * load every needed injection to be ready to create an instance quickly. * * @since 7.2//from w ww . java2 s. c o m */ private void load() { // checks if there's a public constructor without parameters for (Constructor<?> constructor : clazz.getDeclaredConstructors()) { if (Modifier.isPublic(constructor.getModifiers()) && constructor.getParameterTypes().length == 0) { this.constructor = constructor; break; } } if (constructor == null) { throw new MarshallingException("No public constructor found for class " + clazz.getName() + ". Instanciation will not be possible."); } // load instantiation mode Setup setup = loadSetup(clazz); if (setup == null) { throw new MarshallingException("No required @Setup annotation found for class " + clazz.getName() + ". Instanciation will not be possible."); } if (!isReader() && !isWriter()) { throw new MarshallingException( "MarshallerInspector only supports Reader and Writer: you must implement one of this interface for this class: " + clazz.getName()); } if (isReader() && isWriter()) { throw new MarshallingException( "MarshallerInspector only supports either Reader or Writer: you must implement only one of this interface: " + clazz.getName()); } instantiation = setup.mode(); priority = setup.priority(); // load supported mimetype Supports supports = loadSupports(clazz); if (supports != null) { for (String mimetype : supports.value()) { try { MediaType mediaType = MediaType.valueOf(mimetype); this.supports.add(mediaType); } catch (IllegalArgumentException e) { log.warn("In marshaller class " + clazz.getName() + ", the declared mediatype " + mimetype + " cannot be parsed as a mimetype"); } } } if (this.supports.isEmpty()) { log.warn("The marshaller " + clazz.getName() + " does not support any mimetype. You can add some using annotation @Supports"); } // loads the marshalled type and generic type loadMarshalledType(clazz); // load properties that require injection loadInjections(clazz); // warn if several context found if (contextFields.size() > 1) { log.warn("The marshaller " + clazz.getName() + " has more than one context injected property. You probably should use a context from a parent class."); } if (instantiation == Instantiations.SINGLETON) { singleton = getNewInstance(null, true); // the context is empty since it's not required at this place (no // use - just preparing) } }
From source file:org.eclipse.winery.repository.backend.filebased.FilebasedRepository.java
@Override public <T extends TOSCAElementId> SortedSet<T> getNestedIds(GenericId ref, Class<T> idClass) { Path dir = this.id2AbsolutePath(ref); SortedSet<T> res = new TreeSet<T>(); if (!Files.exists(dir)) { // the id has been generated by the exporter without existance test. // This test is done here. return res; }/*from ww w .ja va 2 s . c o m*/ assert (Files.isDirectory(dir)); // list all directories contained in this directory try (DirectoryStream<Path> ds = Files.newDirectoryStream(dir, new OnlyNonHiddenDirectories())) { for (Path p : ds) { XMLId xmlId = new XMLId(p.getFileName().toString(), true); @SuppressWarnings("unchecked") Constructor<T>[] constructors = (Constructor<T>[]) idClass.getConstructors(); assert (constructors.length == 1); Constructor<T> constructor = constructors[0]; assert (constructor.getParameterTypes().length == 2); T id; try { id = constructor.newInstance(ref, xmlId); } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { FilebasedRepository.logger.debug("Internal error at invocation of id constructor", e); // abort everything, return invalid result return res; } res.add(id); } } catch (IOException e) { FilebasedRepository.logger.debug("Cannot close ds", e); } return res; }
From source file:org.evosuite.testcarver.testcase.EvoTestCaseCodeGenerator.java
private boolean hasDefaultConstructor(final Class<?> clazz) { for (final Constructor<?> c : clazz.getConstructors()) { if (c.getParameterTypes().length == 0 && Modifier.isPublic(c.getModifiers())) { return true; }//from ww w . ja v a 2 s . c o m } return false; }
From source file:org.apache.hawq.pxf.plugins.json.PxfUnit.java
/** * Gets an instance of Fragmenter via reflection. * //from w w w . j a v a2s. c o m * Searches for a constructor that has a single parameter of some BaseMetaData type * * @return A Fragmenter instance * @throws Exception * If something bad happens */ protected Fragmenter getFragmenter(InputData meta) throws Exception { Fragmenter fragmenter = null; for (Constructor<?> c : getFragmenterClass().getConstructors()) { if (c.getParameterTypes().length == 1) { for (Class<?> clazz : c.getParameterTypes()) { if (InputData.class.isAssignableFrom(clazz)) { fragmenter = (Fragmenter) c.newInstance(meta); } } } } if (fragmenter == null) { throw new InvalidParameterException( "Unable to find Fragmenter constructor with a BaseMetaData parameter"); } return fragmenter; }
From source file:org.apache.hawq.pxf.plugins.json.PxfUnit.java
/** * Gets an instance of ReadAccessor via reflection. * //w w w .j av a2 s.c o m * Searches for a constructor that has a single parameter of some InputData type * * @return An ReadAccessor instance * @throws Exception * If something bad happens */ protected ReadAccessor getReadAccessor(InputData data) throws Exception { ReadAccessor accessor = null; for (Constructor<?> c : getReadAccessorClass().getConstructors()) { if (c.getParameterTypes().length == 1) { for (Class<?> clazz : c.getParameterTypes()) { if (InputData.class.isAssignableFrom(clazz)) { accessor = (ReadAccessor) c.newInstance(data); } } } } if (accessor == null) { throw new InvalidParameterException( "Unable to find Accessor constructor with a BaseMetaData parameter"); } return accessor; }
From source file:org.apache.hawq.pxf.plugins.json.PxfUnit.java
/** * Gets an instance of IFieldsResolver via reflection. * /*from ww w. j a v a 2 s . co m*/ * Searches for a constructor that has a single parameter of some BaseMetaData type * * @return A IFieldsResolver instance * @throws Exception * If something bad happens */ protected ReadResolver getReadResolver(InputData data) throws Exception { ReadResolver resolver = null; // search for a constructor that has a single parameter of a type of // BaseMetaData to create the accessor instance for (Constructor<?> c : getReadResolverClass().getConstructors()) { if (c.getParameterTypes().length == 1) { for (Class<?> clazz : c.getParameterTypes()) { if (InputData.class.isAssignableFrom(clazz)) { resolver = (ReadResolver) c.newInstance(data); } } } } if (resolver == null) { throw new InvalidParameterException( "Unable to find Resolver constructor with a BaseMetaData parameter"); } return resolver; }