Example usage for java.lang.reflect Constructor newInstance

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

Introduction

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

Prototype

@CallerSensitive
@ForceInline 
public T newInstance(Object... initargs) throws InstantiationException, IllegalAccessException,
        IllegalArgumentException, InvocationTargetException 

Source Link

Document

Uses the constructor represented by this Constructor object to create and initialize a new instance of the constructor's declaring class, with the specified initialization parameters.

Usage

From source file:com.roadmap.common.util.ObjectUtil.java

/**
 * Set the value of the specified property of the specified bean, 
 * no matter which property reference format is used, with no type conversions.
 *
 * @param Object object whose property is to be modified
 * @param String possibly indexed and/or nested name of the property to be modified
 * @param Object value to which this property is to be set 
 *//*w  w w .  j  a  v a  2 s .co m*/
@SuppressWarnings(value = { "unchecked", "rawtypes" })
public static void setPropertyValue(Object vo, String prop, Object value) {
    try {
        if (vo instanceof Map) {
            ((Map) vo).put(prop, value);
        } else {
            PropertyUtils.setProperty(vo, prop, value);
        }
    } catch (IllegalArgumentException iae) {
        try {
            Class cl = PropertyUtils.getPropertyType(vo, prop);
            String clName = cl.getName();
            if (LONG.equalsIgnoreCase(clName)) {
                PropertyUtils.setProperty(vo, prop, Long.valueOf(RoadmapConstants.EMPTY_STRING + value));
            } else if (INT.equalsIgnoreCase(clName) || INTEGER.equalsIgnoreCase(clName)) {
                PropertyUtils.setProperty(vo, prop, Integer.valueOf(RoadmapConstants.EMPTY_STRING + value));
            } else if (BOOLEAN.equalsIgnoreCase(clName)) {
                PropertyUtils.setProperty(vo, prop, Boolean.valueOf(RoadmapConstants.EMPTY_STRING + value));
            } else if (value != null && !value.getClass().getName().equals(clName)) {
                Constructor ctr = cl.getConstructor(value.getClass());
                if (ctr != null) {
                    PropertyUtils.setProperty(vo, prop, ctr.newInstance(value));
                }
            } else {
                PropertyUtils.setProperty(vo, prop, value);
            }
        } catch (Exception e1) {
            // Supress errors
            // LoggingUtil.logError(logger,
            // "PayrollObjectUtility.setPropertyValue for object:"
            // + vo.getClass() + "|property:" + prop
            // + "|value:" + value, e1);
        }
    } catch (Exception e1) {
        // Supress errors
        // LoggingUtil.logError(logger,
        // "PayrollObjectUtility.setPropertyValue for object:"
        // + vo.getClass() + "|property:" + prop + "|value:"
        // + value, e1);
    }

}

From source file:ch.cyberduck.core.SessionFactory.java

public static Session<?> create(final Host host, final X509TrustManager trust, final X509KeyManager key) {
    if (log.isDebugEnabled()) {
        log.debug(String.format("Create session for %s", host));
    }/*from  w  ww. j  a v a2 s. c om*/
    final Protocol protocol = host.getProtocol();
    final String prefix = protocol.getPrefix();

    try {
        final Class<Session> name = (Class<Session>) Class.forName(String.format("%sSession", prefix));
        final Constructor<Session> constructor = ConstructorUtils.getMatchingAccessibleConstructor(name,
                host.getClass(), trust.getClass(), key.getClass());
        final Session<?> session;
        if (null == constructor) {
            log.warn(String.format("No matching constructor for parameter %s, %s, %s", host.getClass(),
                    trust.getClass(), key.getClass()));
            final Constructor<Session> fallback = ConstructorUtils.getMatchingAccessibleConstructor(name,
                    host.getClass());
            if (fallback == null) {
                throw new FactoryException(
                        String.format("No matching constructor for parameter %s", host.getClass()));
            }
            session = fallback.newInstance(host);
        } else {
            session = constructor.newInstance(host, trust, key);
        }
        return session;
    } catch (InstantiationException | InvocationTargetException | ClassNotFoundException
            | IllegalAccessException e) {
        throw new FactoryException(
                String.format("Failure loading session class for %s protocol. Failure %s", protocol, e));
    }
}

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  a2 s. com
    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:hm.binkley.util.XPropsConverter.java

private static <T, E extends Exception> Conversion<T, E> invokeConstructor(final Class<T> token)
        throws NoSuchMethodError {
    try {//from  www . j  a va 2s. c  om
        final Constructor<T> ctor = token.getConstructor(String.class);
        return value -> {
            try {
                return ctor.newInstance(value);
            } catch (final IllegalAccessException e) {
                final IllegalAccessError x = new IllegalAccessError(e.getMessage());
                x.setStackTrace(e.getStackTrace());
                throw x;
            } catch (final InvocationTargetException e) {
                final Throwable root = getRootCause(e);
                final RuntimeException x = new RuntimeException(root);
                x.setStackTrace(root.getStackTrace());
                throw x;
            } catch (final InstantiationException e) {
                final InstantiationError x = new InstantiationError(e.getMessage());
                x.setStackTrace(e.getStackTrace());
                throw x;
            }
        };
    } catch (final NoSuchMethodException ignored) {
        return null;
    }
}

From source file:com.cloudbees.eclipse.core.util.Utils.java

public static <T> T createInstance(final Class<T> clazz, final Class<?>[] types, final Object[] params) {
    try {/*from   w  w w  .j  a  v  a2s. c  om*/
        Constructor<T> cnst;
        cnst = clazz.getConstructor(types);
        return cnst.newInstance(params);
    } catch (SecurityException e) {
    } catch (NoSuchMethodException e) {
    } catch (IllegalArgumentException e) {
    } catch (InstantiationException e) {
    } catch (IllegalAccessException e) {
    } catch (InvocationTargetException e) {
    }
    return null;
}

From source file:com.expressui.core.util.ReflectionUtil.java

/**
 * Creates new instance from the given type, based on given parameter types and args.
 *
 * @param type           class to reflectively instantiate
 * @param <T>            type of the class
 * @param parameterTypes used to find the right constructor
 * @param args           passed to constructor
 * @return new instance//  w w  w .  ja v a  2  s. co m
 */
public static <T> T newInstance(Class<T> type, Class[] parameterTypes, Object[] args) {
    try {
        Constructor constructor = type.getDeclaredConstructor(parameterTypes);
        constructor.setAccessible(true);
        return (T) constructor.newInstance(args);
    } catch (NoSuchMethodException e) {
        throw new RuntimeException(e);
    } catch (InvocationTargetException e) {
        throw new RuntimeException(e);
    } catch (InstantiationException e) {
        throw new RuntimeException(e);
    } catch (IllegalAccessException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.haulmont.bali.util.ReflectionHelper.java

/**
 * Instantiates an object by appropriate constructor.
 * @param cls       class//from www  .j av  a 2  s  .c o  m
 * @param params    constructor arguments
 * @return          created object instance
 * @throws NoSuchMethodException    if the class has no constructor matching the given arguments
 */
@SuppressWarnings("unchecked")
public static <T> T newInstance(Class<T> cls, Object... params) throws NoSuchMethodException {
    Class[] paramTypes = getParamTypes(params);

    Constructor<T> constructor = ConstructorUtils.getMatchingAccessibleConstructor(cls, paramTypes);
    if (constructor == null)
        throw new NoSuchMethodException(
                "Cannot find a matching constructor for " + cls.getName() + " and given parameters");
    try {
        return constructor.newInstance(params);
    } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
        throw new RuntimeException(e);
    }
}

From source file:edu.usc.goffish.gofs.namenode.NameNodeProvider.java

public static IInternalNameNode loadNameNode(Class<? extends IInternalNameNode> type, URI location)
        throws ReflectiveOperationException {
    Constructor<? extends IInternalNameNode> nameNodeConstructor;
    try {//  w  ww  . jav a 2 s  . co  m
        nameNodeConstructor = type.getConstructor(URI.class);
    } catch (NoSuchMethodException e) {
        throw new IllegalArgumentException(type.getName() + " does not have a constructor of the form "
                + type.getSimpleName() + "(" + URI.class.getName() + ")");
    }

    return nameNodeConstructor.newInstance(location);
}

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

public static <T> T newInstance(Class<T> target_class, Object params[], Class<?> classes[]) {
    // Class<?> const_params[] = new Class<?>[params.length];
    // for (int i = 0; i < params.length; i++) {
    // const_params[i] = params[i].getClass();
    // System.err.println("[" + i + "] " + params[i] + " " +
    // params[i].getClass());
    // } // FOR/*from   ww  w. ja  va  2  s.  co m*/

    Constructor<T> constructor = ClassUtil.getConstructor(target_class, classes);
    T ret = null;
    try {
        ret = constructor.newInstance(params);
    } catch (Exception ex) {
        throw new RuntimeException("Failed to create new instance of " + target_class.getSimpleName(), ex);
    }
    return (ret);
}

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

private static Object externalInstance(String nm, Class ty, Object arg) throws IOException {
    try {//from ww w .  ja va2s  .  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());
    }
}