Example usage for java.lang Class getConstructor

List of usage examples for java.lang Class getConstructor

Introduction

In this page you can find the example usage for java.lang Class getConstructor.

Prototype

@CallerSensitive
public Constructor<T> getConstructor(Class<?>... parameterTypes)
        throws NoSuchMethodException, SecurityException 

Source Link

Document

Returns a Constructor object that reflects the specified public constructor of the class represented by this Class object.

Usage

From source file:com.codelanx.codelanxlib.util.exception.Exceptions.java

/**
 * Dynamically constructs a new instance of a {@link RuntimeException}
 * either via a {@link RuntimeException#RuntimeException(String)}
 * constructor or a no-argument constructor
 *
 * @since 0.1.0//from  ww  w  .  j  a  v a 2 s  .  c o m
 * @version 0.1.0
 *
 * @param <T> The {@link RuntimeException} type
 * @param ex The exception class to instantiate
 * @param message The message to add, {@code null} if there is no message
 * @return The newly constructed {@link RuntimeException}
 */
private static <T extends RuntimeException> T newException(Class<T> ex, String message) {
    if (message != null) {
        try {
            Constructor<T> c = ex.getConstructor(String.class);
            c.setAccessible(true);
            return c.newInstance(message);
        } catch (NoSuchMethodException e) {
            Debugger.print(Level.WARNING, String.format(
                    "Class '%s' does not have a String " + "message constructor! Using default constructor...",
                    ex.getName()));
        } catch (SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException
                | InvocationTargetException e) {
            Debugger.error(e, "Error creating new exception instance");
        }
    }
    //Now try here if the previous failed or message wasn't null
    try {
        return ex.newInstance();
    } catch (InstantiationException | IllegalAccessException e) {
        Debugger.error(e, "Error creating new exception instance");
    }
    throw new IllegalArgumentException(String.format(
            "Class '%s' does not have the " + "appropriate constructors to be instantiated", ex.getName()));
}

From source file:de.betterform.xml.config.Config.java

/**
 * Instantiates and defines the singleton instance.
 *
 * @param stream/*from  ww  w . ja  va  2s  .  co  m*/
 *            InputStream from where the configuration will be read.
 * @throws XFormsConfigException
 *             If the configuration could not be loaded.
 */
private static void initSingleton(InputStream stream) throws XFormsConfigException {

    //gets the concrete config class name from a system property
    //using DefaultConfig if the property is not set
    String configClassName = System.getProperty(Config.class.getName(), DefaultConfig.class.getName());

    try {
        //uses reflection to get the constructor
        //(the constructor must have public visibility)
        Class classRef = Class.forName(configClassName, true, Config.class.getClassLoader());

        Constructor construct = classRef.getConstructor(new Class[] { InputStream.class });

        //initializes the singleton invoking the constructor
        SINGLETON = (Config) construct.newInstance(new Object[] { stream });

    } catch (Exception e) {
        throw new XFormsConfigException(e);
    }
}

From source file:com.oltpbenchmark.util.ClassUtil.java

/**
 * //from   w  w  w.  j  a  va  2 s .c o m
 * @param <T>
 * @param target_class
 * @param params
 * @return
 */
@SuppressWarnings("unchecked")
public static <T> Constructor<T> getConstructor(Class<T> target_class, Class<?>... params) {
    NoSuchMethodException error = null;
    try {
        return (target_class.getConstructor(params));
    } catch (NoSuchMethodException ex) {
        // The first time we get this it can be ignored
        // We'll try to be nice and find a match for them
        error = ex;
    }
    assert (error != null);

    if (LOG.isDebugEnabled()) {
        LOG.debug("TARGET CLASS:  " + target_class);
        LOG.debug("TARGET PARAMS: " + Arrays.toString(params));
    }

    List<Class<?>> paramSuper[] = (List<Class<?>>[]) new List[params.length];
    for (int i = 0; i < params.length; i++) {
        paramSuper[i] = ClassUtil.getSuperClasses(params[i]);
        if (LOG.isDebugEnabled())
            LOG.debug("  SUPER[" + params[i].getSimpleName() + "] => " + paramSuper[i]);
    } // FOR

    for (Constructor<?> c : target_class.getConstructors()) {
        Class<?> cTypes[] = c.getParameterTypes();
        if (LOG.isDebugEnabled()) {
            LOG.debug("CANDIDATE: " + c);
            LOG.debug("CANDIDATE PARAMS: " + Arrays.toString(cTypes));
        }
        if (params.length != cTypes.length)
            continue;

        for (int i = 0; i < params.length; i++) {
            List<Class<?>> cSuper = ClassUtil.getSuperClasses(cTypes[i]);
            if (LOG.isDebugEnabled())
                LOG.debug("  SUPER[" + cTypes[i].getSimpleName() + "] => " + cSuper);
            if (CollectionUtils.intersection(paramSuper[i], cSuper).isEmpty() == false) {
                return ((Constructor<T>) c);
            }
        } // FOR (param)
    } // FOR (constructors)
    throw new RuntimeException("Failed to retrieve constructor for " + target_class.getSimpleName(), error);
}

From source file:edu.kit.dama.staging.entities.AdalapiProtocolConfiguration.java

/**
 * ProtocolConfiguration factory method for creating a new
 * ProtocolConfiguration that can be persisted afterwards. Within this
 * method, a configuration identifier is generated using {@link #getProtocolIdentifier(java.net.URL)
 * }. All other arguments are checked and set in the returned entity.
 *
 * @param pUrl A sample URL used to generate the unique identifier.
 * @param protocolClass The protocol implementation class.
 * @param authenticatorClass The authenticator class.
 * @param pCustomProperties Custom properties that can be used while
 * configuring both, the protocol and the authenticator.
 *
 * @return An AdalapiProtocolConfiguration.
 *
 * @throws InitializationError If e.g. protocol- or authenticator class
 * could not be found or if customProperties could not be handled.
 *///  w ww .j  ava  2s. c o m
public final static AdalapiProtocolConfiguration factoryConfiguration(URL pUrl, String protocolClass,
        String authenticatorClass, Map<String, Object> pCustomProperties) throws InitializationError {
    AdalapiProtocolConfiguration config = new AdalapiProtocolConfiguration();
    config.setIdentifier(getProtocolIdentifier(pUrl));

    try {
        Class protocolClazz = Thread.currentThread().getContextClassLoader().loadClass(protocolClass.trim());
        Constructor defaultConst;
        try {
            defaultConst = protocolClazz.getConstructor(new Class[] { URL.class, Configuration.class });
        } catch (NoSuchMethodException nsme) {
            defaultConst = protocolClazz.getConstructor(new Class[] { URL.class });
        }
        config.setProtocolClass(protocolClass);
    } catch (ClassNotFoundException | NoSuchMethodException ex) {
        throw new InitializationError("Invalid protocol class '" + protocolClass + "'.", ex);
    }
    try {
        Class authenticatorClazz = Thread.currentThread().getContextClassLoader()
                .loadClass(authenticatorClass.trim());
        config.setAuthenticatorClass(authenticatorClass);
    } catch (ClassNotFoundException ex) {
        throw new InitializationError("Invalid authenticator class '" + authenticatorClass + "'.", ex);
    }

    config.setCustomPropertiesAsObject(pCustomProperties);
    return config;
}

From source file:dk.itst.oiosaml.sp.service.util.Utils.java

public static Map<String, SAMLHandler> getHandlers(Configuration config, ServletContext servletContext) {
    Map<String, SAMLHandler> handlers = new HashMap<String, SAMLHandler>();

    for (Iterator<?> i = config.getKeys(); i.hasNext();) {
        String key = (String) i.next();
        if (!key.startsWith("oiosaml-sp.protocol.endpoints."))
            continue;
        log.debug("Checking " + key);

        try {//from   www  . j a v  a  2  s.  co m
            Class<?> c = Class.forName(config.getString(key));
            SAMLHandler instance;
            try {
                Constructor<?> constructor = c.getConstructor(Configuration.class);
                instance = (SAMLHandler) constructor.newInstance(config);
            } catch (NoSuchMethodException e) {
                try {
                    Constructor<?> constructor = c.getConstructor(ServletContext.class);
                    instance = (SAMLHandler) constructor.newInstance(servletContext);
                } catch (NoSuchMethodException ex) {
                    instance = (SAMLHandler) c.newInstance();
                }
            }

            //            log.info("instance:" + instance.toString()); // pdurbin
            handlers.put(key.substring(key.lastIndexOf('.') + 1), instance);

        } catch (Exception e) {
            log.error("Unable to instantiate " + key + ": " + config.getString(key), e);
            throw new RuntimeException(e);
        }

    }

    return handlers;
}

From source file:com.bluecloud.ioc.classloader.ClassHandler.java

/**
 * <h3>Class</h3>/*from www  .  ja v  a  2s. co  m*/
 * 
 * @param clazz
 * @return
 * @throws ClassNotFoundException
 * @throws IllegalAccessException
 * @throws InstantiationException
 * @throws NoSuchMethodException
 * @throws InvocationTargetException
 * @throws SecurityException
 * @throws IllegalArgumentException
 */
private static Object getClassNewInstrance(Class<?> clazz)
        throws ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException,
        SecurityException, InvocationTargetException, NoSuchMethodException {
    if (clazz == null) {
        throw new ClassNotFoundException();
    }
    return clazz.getConstructor((Class[]) null).newInstance((Object[]) null);
}

From source file:net.contrapunctus.rngzip.io.RNGZSettings.java

private static Object externalInstance(String nm, Class ty, Object arg) throws IOException {
    try {//  w w w.  j av a 2s.c o m
        Class c = Class.forName(nm);
        Constructor k = c.getConstructor(ty);
        return k.newInstance(arg);
    } catch (Exception x) {
        throw new IOException(x.getMessage());
    }
}

From source file:de.unisb.cs.st.javalanche.mutation.runtime.testDriver.junit.Junit4MutationTestDriver.java

private static Runner getRunner(Description desc, boolean useSuite) {
    String className = getClassName(desc);
    Runner tcr = null;/*from   w  w w. j  a v  a 2s.  co  m*/
    try {
        Class<?> clazz;
        clazz = Class.forName(className);
        logger.info("Creating Runner for " + className);
        Class<? extends Runner> runWithRunner = getRunWithRunner(clazz, useSuite);
        Constructor<? extends Runner> constructor = runWithRunner.getConstructor(Class.class);
        tcr = constructor.newInstance(clazz);
        // logger.debug("Runner Type " + tcr.getClass());
    } catch (ClassNotFoundException e) {
        throw new RuntimeException(e);
    } catch (SecurityException e) {
        throw new RuntimeException(e);
    } catch (NoSuchMethodException e) {
        throw new RuntimeException(e);
    } catch (IllegalArgumentException e) {
        throw new RuntimeException(e);
    } catch (InstantiationException e) {
        throw new RuntimeException(e);
    } catch (IllegalAccessException e) {
        throw new RuntimeException(e);
    } catch (InvocationTargetException e) {
        logger.warn("Invocation Exception ", e);
        throw new RuntimeException(e);
    }
    return tcr;
}

From source file:net.big_oh.common.web.filters.ipaddress.IPAddressFilter.java

private static IPAddressFilterRule instantiateIPAddressFilterRule(String className, String constructorParam) {

    IPAddressFilterRule newIPAddressFilterRule = null;

    try {/*  w  w  w . j a v a  2s  . co m*/
        // Get the class declared in the FilterConfig parameter.
        Class<?> filterRuleClass = Class.forName(className);

        // Try to instantiate an instance of the IPAddressFilterRule class
        // Look for an appropriate constructor that takes a single
        // java.lang.String
        Constructor<?> constructor = filterRuleClass.getConstructor(String.class);

        newIPAddressFilterRule = (IPAddressFilterRule) constructor.newInstance(constructorParam);
    } catch (ClassNotFoundException cnfe) {
        logger.error("Could not find a class named " + className);
    } catch (NoSuchMethodException e) {
        logger.error("Could not instantiate an instance of class " + className + ".");
        logger.error(e);
    } catch (InstantiationException e) {
        logger.error("Could not instantiate an instance of class " + className + ".");
        logger.error(e);
    } catch (IllegalAccessException e) {
        logger.error("Could not instantiate an instance of class " + className + ".");
        logger.error(e);
    } catch (InvocationTargetException e) {
        logger.error("Could not instantiate an instance of class " + className + ".");
        logger.error(e);
    } catch (RuntimeException e) {
        logger.error("Could not instantiate an instance of class " + className + ".");
        logger.error(e);
    }

    return newIPAddressFilterRule;

}

From source file:edu.brown.utils.ClassUtil.java

/**
 * Grab the constructor for the given target class with the provided input parameters.
 * This method will first try to find an exact match for the parameters, and if that
 * fails then it will be smart and try to find one with the input parameters super classes. 
 * @param <T>//  w  w w. j a  va  2  s.  c o m
 * @param target_class
 * @param params
 * @return
 */
@SuppressWarnings("unchecked")
public static <T> Constructor<T> getConstructor(Class<T> target_class, Class<?>... params) {
    NoSuchMethodException error = null;
    try {
        return (target_class.getConstructor(params));
    } catch (NoSuchMethodException ex) {
        // The first time we get this it can be ignored
        // We'll try to be nice and find a match for them
        error = ex;
    }
    assert (error != null);

    if (debug.val) {
        LOG.debug("TARGET CLASS:  " + target_class);
        LOG.debug("TARGET PARAMS: " + Arrays.toString(params));
    }

    final int num_params = (params != null ? params.length : 0);
    List<Class<?>> paramSuper[] = (List<Class<?>>[]) new List[num_params];
    for (int i = 0; i < num_params; i++) {
        paramSuper[i] = ClassUtil.getSuperClasses(params[i]);
        if (debug.val)
            LOG.debug("  SUPER[" + params[i].getSimpleName() + "] => " + paramSuper[i]);
    } // FOR

    for (Constructor<?> c : target_class.getConstructors()) {
        Class<?> cTypes[] = c.getParameterTypes();
        if (debug.val) {
            LOG.debug("CANDIDATE: " + c);
            LOG.debug("CANDIDATE PARAMS: " + Arrays.toString(cTypes));
        }
        if (params.length != cTypes.length)
            continue;

        for (int i = 0; i < num_params; i++) {
            List<Class<?>> cSuper = ClassUtil.getSuperClasses(cTypes[i]);
            if (debug.val)
                LOG.debug("  SUPER[" + cTypes[i].getSimpleName() + "] => " + cSuper);
            if (CollectionUtils.intersection(paramSuper[i], cSuper).isEmpty() == false) {
                return ((Constructor<T>) c);
            }
        } // FOR (param)
    } // FOR (constructors)
    throw new RuntimeException("Failed to retrieve constructor for " + target_class.getSimpleName(), error);
}