Example usage for java.lang Class newInstance

List of usage examples for java.lang Class newInstance

Introduction

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

Prototype

@CallerSensitive
@Deprecated(since = "9")
public T newInstance() throws InstantiationException, IllegalAccessException 

Source Link

Document

Creates a new instance of the class represented by this Class object.

Usage

From source file:com.nerve.commons.repository.utils.ConvertUtils.java

/**
 * ????javaBean?javabeanproperties?//from   w  w  w  .jav  a2 s  . c om
 * ?nametitle
 * javabeannamevalue
 * properties
 * {
 *     name:name,
 *     title:value
 * }
 * ?name?javabeannametitle?value
 * @param collection
 * @param properties
 * @return
 */
public static List convertElementPropertyToBeanList(final Collection collection,
        final Map<String, String> properties, Class<?> toType) {
    List list = new ArrayList();

    try {
        for (Object obj : collection) {
            Object bean = toType.newInstance();
            for (String key : properties.keySet()) {
                PropertyUtils.setProperty(bean, properties.get(key), PropertyUtils.getProperty(obj, key));
            }
            list.add(bean);
        }
    } catch (Exception e) {
        throw ReflectionUtils.convertReflectionExceptionToUnchecked(e);
    }

    return list;
}

From source file:org.openlmis.fulfillment.testutils.DtoGenerator.java

private static <T> void generate(Class<T> clazz) {
    Object instance;/*  ww w .j  a v a2  s  .c o  m*/

    try {
        instance = clazz.newInstance();
    } catch (Exception exp) {
        throw new IllegalStateException("Missing no args constructor", exp);
    }

    for (PropertyDescriptor descriptor : PropertyUtils.getPropertyDescriptors(clazz)) {
        if ("class".equals(descriptor.getName())) {
            continue;
        }

        if (null == descriptor.getReadMethod() || null == descriptor.getWriteMethod()) {
            // we support only full property (it has to have a getter and setter)
            continue;
        }

        try {
            Object value = generateValue(clazz, descriptor.getPropertyType());
            PropertyUtils.setProperty(instance, descriptor.getName(), value);
        } catch (Exception exp) {
            throw new IllegalStateException("Can't set value for property: " + descriptor.getName(), exp);
        }
    }

    REFERENCES.put(clazz, instance);
}

From source file:ch.cyberduck.core.aquaticprime.LicenseFactory.java

/**
 * @param file File to parse// w  w  w .ja v a 2s . co m
 * @return Read license from file
 */
public static License get(final Local file) {
    final String clazz = preferences.getProperty("factory.licensefactory.class");
    if (null == clazz) {
        throw new FactoryException();
    }
    try {
        final Class<LicenseFactory> name = (Class<LicenseFactory>) Class.forName(clazz);
        return name.newInstance().open(file);
    } catch (InstantiationException | ClassNotFoundException | IllegalAccessException e) {
        throw new FactoryException(e.getMessage(), e);
    }
}

From source file:org.onesun.atomator.adaptors.AdaptorFactory.java

public static Adaptor newAdaptor(Channel channel, String feedURL, boolean fullText) {
    Adaptor adaptor = null;// www  .  ja va2 s .co m

    String type = channel.getEntry().getChannelType();
    if (adaptors.containsKey(type) == false) {
        type = GENERIC_ADAPTOR_NAME;
    }

    logger.info("Resolving class [asked]: " + channel + " [giving]: " + type);
    Class<?> clazz = adaptors.get(type);
    if (clazz != null) {
        try {
            adaptor = (Adaptor) clazz.newInstance();
            adaptor.setChannel(channel);

            if (feedURL != null) {
                adaptor.setFeedURL(feedURL);
            }

            adaptor.setFullText(fullText);
        } catch (InstantiationException e) {
            logger.error("Instantiation Exception while loading adaptors : " + e.getMessage());
            e.printStackTrace();

        } catch (IllegalAccessException e) {
            logger.error("Illegal Access Exception while loading adaptors : " + e.getMessage());
            e.printStackTrace();
        }
    }

    return adaptor;
}

From source file:iterator.Reflection.java

public static <T> T newInstance(Class<T> clazz, Object... args) {
    try {//from   w  w  w  .j  a  v  a 2 s. c o m
        return args != null && args.length > 0 ? ConstructorUtils.invokeConstructor(clazz, args)
                : clazz.newInstance();
    } catch (Exception e) {
        throw new IllegalArgumentException(e);
    }
}

From source file:com.fengduo.bee.commons.component.ObjectArrayDataBinder.java

@SuppressWarnings("unchecked")
public static <E> E[] createArray(Class<E> clazz, int capacity) {
    E[] array = (E[]) Array.newInstance(clazz, capacity);
    for (int i = 0; i < capacity; i++) {
        try {/*from w  ww  .java2 s  .  c o  m*/
            array[i] = clazz.newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }
    return array;
}

From source file:com.tacitknowledge.util.migration.jdbc.util.SqlUtil.java

/**
 * Established and returns a connection based on the specified parameters.
 *
 * @param driver the JDBC driver to use//from  w  w  w.j a  va2s.c om
 * @param url    the database URL
 * @param user   the username
 * @param pass   the password
 * @return a JDBC connection
 * @throws ClassNotFoundException if the driver could not be loaded
 * @throws SQLException           if a connnection could not be made to the database
 */
public static Connection getConnection(String driver, String url, String user, String pass)
        throws ClassNotFoundException, SQLException {
    Connection conn = null;
    try {
        Class.forName(driver);
        log.debug("Getting Connection to " + url);
        conn = DriverManager.getConnection(url, user, pass);
    } catch (Exception e) {
        /* work around for DriverManager 'feature'.  
         * In some cases, the jdbc driver jar is injected into a new 
         * child classloader (for example, maven provides different 
         * class loaders for different build lifecycle phases). 
         * 
         * Since DriverManager uses the calling class' loader instead 
         * of the current context's loader, it fails to find the driver.
         * 
         * Our work around is to give the current context's class loader 
         * a shot at finding the driver in cases where DriverManager fails.  
         * This 'may be' a security hole which is why DriverManager implements 
         * things in such a way that it doesn't use the current thread context class loader.
         */
        try {
            Class driverClass = Class.forName(driver, true, Thread.currentThread().getContextClassLoader());
            Driver driverImpl = (Driver) driverClass.newInstance();
            Properties props = new Properties();
            props.put("user", user);
            props.put("password", pass);
            conn = driverImpl.connect(url, props);
        } catch (InstantiationException ie) {
            log.debug(ie);
            throw new SQLException(ie.getMessage());
        } catch (IllegalAccessException iae) {
            log.debug(iae);
            throw new SQLException(iae.getMessage());
        }
    }

    return conn;
}

From source file:Main.java

public static void replaceFragment(FragmentManager manager, Class<? extends Fragment> fragmentClass,
        boolean isAddToBackStack) {

    Fragment fragment = manager.findFragmentByTag(fragmentClass.getSimpleName());

    if (null == fragment) {
        try {//w w w .  ja  va 2  s  .c  om

            fragment = fragmentClass.newInstance();

        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

    }

    FragmentTransaction ft = manager.beginTransaction();
    ft.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out, android.R.anim.fade_in,
            android.R.anim.fade_out);
    if (!fragment.isAdded()) {
        ft.replace(android.R.id.content, fragment, fragment.getClass().getSimpleName());
        if (isAddToBackStack) {
            ft.addToBackStack(null);
        }
    }
    ft.commit();

}

From source file:com.lioland.harmony.web.dao.ODBClass.java

private static Object transform(ODocument doc, Class cls) {
    Object ob = null;/* w  w w. jav a 2s  .co m*/
    try {
        ob = cls.newInstance();
        fillObject(doc, ob);
    } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException
            | ClassNotFoundException ex) {
        Logger.getLogger(ODBClass.class.getName()).log(Level.SEVERE, null, ex);
    }
    return ob;
}

From source file:net.aepik.alasca.plugin.schemaquery.SchemaQueryTool.java

/**
 * Create a SchemaSyntax object from a valid syntax name.
 * @param String syntaxName A valid syntax name.
 * @return SchemaSyntax/*w w  w  .  j a va2  s.co m*/
 */
private static SchemaSyntax createSchemaSyntax(String syntaxName) {
    SchemaSyntax syntax = null;
    try {
        String syntaxClassName = Schema.getSyntaxPackageName() + "." + syntaxName;
        @SuppressWarnings("unchecked")
        Class<SchemaSyntax> syntaxClass = (Class<SchemaSyntax>) Class.forName(syntaxClassName);
        syntax = syntaxClass.newInstance();
    } catch (Exception e) {
    }
    ;
    return syntax;
}