Example usage for java.lang.reflect Constructor getGenericParameterTypes

List of usage examples for java.lang.reflect Constructor getGenericParameterTypes

Introduction

In this page you can find the example usage for java.lang.reflect Constructor getGenericParameterTypes.

Prototype

@Override
public Type[] getGenericParameterTypes() 

Source Link

Usage

From source file:Main.java

public static void main(String... args) {
    Constructor[] ctors = Console.class.getDeclaredConstructors();
    Constructor ctor = null;
    for (int i = 0; i < ctors.length; i++) {
        ctor = ctors[i];/*from w ww. j av a  2s  . c  om*/
        if (ctor.getGenericParameterTypes().length == 0)
            break;
    }

    try {
        ctor.setAccessible(true);
        Console c = (Console) ctor.newInstance();
        Field f = c.getClass().getDeclaredField("cs");
        f.setAccessible(true);
        out.format("Console charset         :  %s%n", f.get(c));
        out.format("Charset.defaultCharset():  %s%n", Charset.defaultCharset());

        // production code should handle these exceptions more gracefully
    } catch (InstantiationException x) {
        x.printStackTrace();
    } catch (InvocationTargetException x) {
        x.printStackTrace();
    } catch (IllegalAccessException x) {
        x.printStackTrace();
    } catch (NoSuchFieldException x) {
        x.printStackTrace();
    }
}

From source file:ConstructorSift.java

public static void main(String... args) {
    try {//from  w w  w. j  a  va 2s . com
        Class<?> cArg = Class.forName(args[1]);

        Class<?> c = Class.forName(args[0]);
        Constructor[] allConstructors = c.getDeclaredConstructors();
        for (Constructor ctor : allConstructors) {
            Class<?>[] pType = ctor.getParameterTypes();
            for (int i = 0; i < pType.length; i++) {
                if (pType[i].equals(cArg)) {
                    out.format("%s%n", ctor.toGenericString());

                    Type[] gpType = ctor.getGenericParameterTypes();
                    for (int j = 0; j < gpType.length; j++) {
                        char ch = (pType[j].equals(cArg) ? '*' : ' ');
                        out.format("%7c%s[%d]: %s%n", ch, "GenericParameterType", j, gpType[j]);
                    }
                    break;
                }
            }
        }

        // production code should handle this exception more gracefully
    } catch (ClassNotFoundException x) {
        x.printStackTrace();
    }
}

From source file:Main.java

private static Constructor<?> getDefaultConstructor(@NonNull Class<?> cls) {
    final Constructor[] ctors = cls.getDeclaredConstructors();
    Constructor ctor = null;
    for (Constructor ct : ctors) {
        ctor = ct;/*from   w ww. j a va2s .  c  o  m*/
        if (ctor.getGenericParameterTypes().length == 0)
            break;
    }
    if (ctor == null)
        throw new IllegalStateException("No default constructor found for " + cls.getName());
    ctor.setAccessible(true);
    return ctor;
}

From source file:com.curl.orb.servlet.InstanceManagementUtil.java

/**
 * Get Generic types of constructor's parameters.
 */// w  w w.jav  a  2s  .  c o m
public static Class<?>[][] getGenericConstructorParameterTypes(Constructor<?> constructor) {
    Type[] genericType = constructor.getGenericParameterTypes();
    int len = genericType.length;
    Class<?>[][] genericTypes = new Class<?>[len][];
    for (int i = 0; i < len; i++)
        genericTypes[i] = getGenericTypes(genericType[i]);
    return genericTypes;
}

From source file:com.github.tomakehurst.wiremock.matching.StringValuePatternJsonDeserializer.java

@SuppressWarnings("unchecked")
private static Constructor<? extends StringValuePattern> findConstructor(
        Class<? extends StringValuePattern> clazz) {
    Optional<Constructor<?>> optionalConstructor = tryFind(asList(clazz.getDeclaredConstructors()),
            new Predicate<Constructor<?>>() {
                @Override/*from w  w w . j  av a2  s  . co  m*/
                public boolean apply(Constructor<?> input) {
                    return input.getParameterTypes().length == 1
                            && input.getGenericParameterTypes()[0].equals(String.class);
                }
            });

    if (!optionalConstructor.isPresent()) {
        throw new IllegalStateException(
                "Constructor for " + clazz.getSimpleName() + " must have a single string argument constructor");
    }

    return (Constructor<? extends StringValuePattern>) optionalConstructor.get();
}

From source file:com.github.juanmf.java2plant.Parser.java

protected static void addConstructorUses(Set<Relation> relations, Class<?> fromType, Constructor<?> c) {
    Type[] genericParameterTypes = c.getGenericParameterTypes();
    for (int i = 0; i < genericParameterTypes.length; i++) {
        addConstructorUse(relations, fromType, genericParameterTypes[i], c);
    }//w w  w .j  a  va  2s  .  c  o m
}

From source file:org.alfresco.module.org_alfresco_module_rm.api.PublicAPITestUtil.java

/**
 * Get all types referenced by the supplied constructor (i.e. the parameters and exceptions).
 *
 * @param constructor The constructor to analyse.
 * @return The set of types.//from  w  w  w.  j  av  a  2 s  .c  o m
 */
private static Set<Type> getTypesFromConstructor(Constructor<?> constructor) {
    Set<Type> methodTypes = new HashSet<>();
    methodTypes.addAll(Sets.newHashSet(constructor.getGenericParameterTypes()));
    methodTypes.addAll(Sets.newHashSet(constructor.getGenericExceptionTypes()));
    return methodTypes;
}

From source file:gdt.data.entity.facet.ExtensionHandler.java

/**
 * Get the handler instance.  //ww w .  j a  va2 s  .  c om
 *  @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;
    }

}

From source file:com.espertech.esper.util.MethodResolver.java

public static Constructor resolveCtor(Class declaringClass, Class[] paramTypes)
        throws EngineNoSuchCtorException {
    // Get all the methods for this class
    Constructor[] ctors = declaringClass.getConstructors();

    Constructor bestMatch = null;
    int bestConversionCount = -1;

    // Examine each method, checking if the signature is compatible
    Constructor conversionFailedCtor = null;
    for (Constructor ctor : ctors) {
        // Check the modifiers: we only want public
        if (!Modifier.isPublic(ctor.getModifiers())) {
            continue;
        }/*w  ww . ja  v  a2 s .c  o  m*/

        // Check the parameter list
        int conversionCount = compareParameterTypesNoContext(ctor.getParameterTypes(), paramTypes, null, null,
                ctor.getGenericParameterTypes());

        // Parameters don't match
        if (conversionCount == -1) {
            conversionFailedCtor = ctor;
            continue;
        }

        // Parameters match exactly
        if (conversionCount == 0) {
            bestMatch = ctor;
            break;
        }

        // No previous match
        if (bestMatch == null) {
            bestMatch = ctor;
            bestConversionCount = conversionCount;
        } else {
            // Current match is better
            if (conversionCount < bestConversionCount) {
                bestMatch = ctor;
                bestConversionCount = conversionCount;
            }
        }

    }

    if (bestMatch != null) {
        return bestMatch;
    } else {
        StringBuilder parameters = new StringBuilder();
        String message = "Constructor not found for " + declaringClass.getSimpleName() + " taking ";
        if (paramTypes != null && paramTypes.length != 0) {
            String appendString = "";
            for (Object param : paramTypes) {
                parameters.append(appendString);
                if (param == null) {
                    parameters.append("(null)");
                } else {
                    parameters.append(param.toString());
                }
                appendString = ", ";
            }
            message += "('" + parameters + "')'";
        } else {
            message += "no parameters";
        }
        throw new EngineNoSuchCtorException(message, conversionFailedCtor);
    }
}

From source file:org.jenkinsci.plugins.workflow.structs.DescribableHelper.java

/**
 * Creates an instance of a class via {@link DataBoundConstructor} and {@link DataBoundSetter}.
 * <p>The arguments may be primitives (as wrappers) or {@link String}s if that is their declared type.
 * {@link Character}s, {@link Enum}s, and {@link URL}s may be represented by {@link String}s.
 * Other object types may be passed in raw? as well, but JSON-like structures are encouraged instead.
 * Specifically a {@link List} may be used to represent any list- or array-valued argument.
 * A {@link Map} with {@link String} keys may be used to represent any class which is itself data-bound.
 * In that case the special key {@link #CLAZZ} is used to specify the {@link Class#getName};
 * or it may be omitted if the argument is declared to take a concrete type;
 * or {@link Class#getSimpleName} may be used in case the argument type is {@link Describable}
 * and only one subtype is registered (as a {@link Descriptor}) with that simple name.
 *///w  w w  .  j a va 2s  .c o  m
public static <T> T instantiate(Class<? extends T> clazz, Map<String, ?> arguments) throws Exception {
    String[] names = loadConstructorParamNames(clazz);
    Constructor<T> c = findConstructor(clazz, names.length);
    Object[] args = buildArguments(clazz, arguments, c.getGenericParameterTypes(), names, true);
    T o = c.newInstance(args);
    injectSetters(o, arguments);
    return o;
}