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:org.jdbcluster.metapersistence.cluster.ClusterFactory.java

/**
 * creates an instance of a Cluster/*ww  w  .j av  a 2  s  .co m*/
 * Cluster interceptor is <b>not called</b> if dao!=null
 * Cluster privileges are <b>not checked</b> if dao!=null 
 * @param clusterClass class of cluster
 * @param dao dao object to be presetted
 * @param daoIsPersistent if dao Object is persistent dont call interceptor and pivilegeInterceptor
 * @param user saves the given User object into the newly created Cluster object.
 * @return the new Cluster instance.
 */
@SuppressWarnings("unchecked")
public static <T extends Cluster> T newInstance(Class<? extends ICluster> clusterClass, Object dao,
        boolean daoIsPersistent, IUser user) {

    Assert.notNull(clusterClass, "Class<?> may not be null");

    PrivilegeChecker pc = PrivilegeCheckerImpl.getInstance();
    Cluster cluster = null;
    try {
        //create a new instance with given classname
        cluster = (Cluster) clusterClass.newInstance();
    } catch (InstantiationException e) {
        throw new ClusterTypeException(
                "specified class [" + clusterClass.getName()
                        + "] object cannot be instantiated because it is an interface or is an abstract class",
                e);
    } catch (IllegalAccessException e) {
        throw new ClusterTypeException(
                "the currently executed ctor for class [" + clusterClass.getName() + "] does not have access",
                e);
    }
    if (user != null) {
        cluster.setUser(user);
    }
    if (dao != null)
        cluster.setDao(dao);
    else {
        DaoLink classAnno = clusterClass.getAnnotation(DaoLink.class);
        if (classAnno != null)
            cluster.setDao(Dao.newInstance(classAnno.dAOClass()));
    }

    if (!daoIsPersistent) {
        /*
         * call of cluster interceptor
         */
        if (!getClusterInterceptor().clusterNew(cluster))
            throw new ConfigurationException(
                    "ClusterInterceptor [" + getClusterInterceptor().getClass().getName() + "] returned false");

        /*
         * privilege check (only static privileges are checked)
         */
        if (cluster instanceof PrivilegedCluster) {
            if (!pc.userPrivilegeIntersect(user, (PrivilegedCluster) cluster))
                throw new PrivilegeException(
                        "No sufficient privileges for new Cluster class [" + clusterClass.getName() + "]");
        }
    }
    cluster.setClusterType(ClusterTypeFactory.newInstance(clusterClass));
    return (T) cluster;
}

From source file:com.all.shared.json.JsonConverter.java

public static <T extends Collection<V>, V> T toTypedCollection(String json, Class<T> collectionType,
        Class<V> contentType) {
    T collection = null;//from   w w  w.j  a  v  a 2  s  . c o m
    JSONArray jsonCollection = JSONArray.fromObject(json);
    try {
        collection = collectionType.newInstance();
        Iterator<?> iterator = jsonCollection.iterator();
        while (iterator.hasNext()) {
            try {
                if (PRIMITIVES.contains(contentType)) {
                    collection.add(
                            contentType.getConstructor(String.class).newInstance(iterator.next().toString()));
                } else {
                    collection.add(toBean(iterator.next().toString(), contentType));
                }
            } catch (Exception e) {
                log.warn("Could not read a " + contentType.getSimpleName() + " from a json array.", e);
            }
        }
    } catch (Exception e) {
        return toCollection(json, collectionType);
    }
    return collection;
}

From source file:com.fengduo.bee.commons.core.lang.BeanUtils.java

public static <T extends Object> List<T> convert(IPreHandle<T> ipHandle, Class<T> clazz, Collection<?> raw,
        ValueEditable... specialConverts) {
    if (Argument.isEmpty(raw)) {
        return Collections.emptyList();
    }//from www  .  j a  v a2  s .co m
    List<T> data = new ArrayList<T>(raw.size());
    for (Object obj : raw) {
        T vo;
        try {
            vo = clazz.newInstance();
            copyProperties(vo, obj, specialConverts);
            data.add(vo);

            // ?
            ipHandle.init(vo, obj);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return data;
}

From source file:com.fengduo.bee.commons.core.lang.BeanUtils.java

/**
 * ? init?/*from www .  j av  a2s . c  o m*/
 * 
 * @param clazz
 * @param raw
 * @param specialConverts
 * @return
 */
public static <T extends Object> List<T> convert(Class<T> clazz, Collection<?> raw,
        ValueEditable... specialConverts) {
    if (Argument.isEmpty(raw)) {
        return Collections.emptyList();
    }
    List<T> data = new ArrayList<T>(raw.size());
    for (Object obj : raw) {
        T vo;
        try {
            vo = clazz.newInstance();
            copyProperties(vo, obj, specialConverts);
            data.add(vo);

            // ?
            optInitMethod(vo);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return data;
}

From source file:ch.entwine.weblounge.common.impl.scheduler.QuartzJob.java

/**
 * Initializes this job from an XML node that was generated using
 * {@link #toXml()}./*from  w w w.  j  a  v a  2 s.  co  m*/
 * 
 * @param context
 *          the job node
 * @param xpathProcessor
 *          xpath processor to use
 * @throws IllegalStateException
 *           if the job cannot be parsed
 * @see #toXml()
 */
@SuppressWarnings("unchecked")
public static Job fromXml(Node config, XPath xPathProcessor) throws IllegalStateException {

    CronJobTrigger jobTrigger = null;
    Dictionary<String, Object> ctx = new Hashtable<String, Object>();
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();

    // Main attributes
    String identifier = XPathHelper.valueOf(config, "@id", xPathProcessor);

    // Implementation class
    String className = XPathHelper.valueOf(config, "m:class", xPathProcessor);
    Class<? extends JobWorker> c;
    try {
        c = (Class<? extends JobWorker>) classLoader.loadClass(className);
        c.newInstance(); // Create an instance just to make sure we catch any errors right here
    } catch (ClassNotFoundException e) {
        throw new IllegalStateException(
                "Implementation " + className + " for job '" + identifier + "' not found", e);
    } catch (InstantiationException e) {
        throw new IllegalStateException(
                "Error instantiating impelementation " + className + " for job '" + identifier + "'", e);
    } catch (IllegalAccessException e) {
        throw new IllegalStateException(
                "Access violation instantiating implementation " + className + " for job '" + identifier + "'",
                e);
    } catch (Throwable t) {
        throw new IllegalStateException(
                "Error loading implementation " + className + " for job '" + identifier + "'", t);
    }

    // Read execution schedule
    String schedule = XPathHelper.valueOf(config, "m:schedule", xPathProcessor);
    if (schedule == null)
        throw new IllegalStateException("No schedule has been defined for job '" + identifier + "'");
    jobTrigger = new CronJobTrigger(schedule);

    // Read options
    Node nodes = XPathHelper.select(config, "m:options", xPathProcessor);
    OptionsHelper options = OptionsHelper.fromXml(nodes, xPathProcessor);
    for (Map.Entry<String, Map<Environment, List<String>>> entry : options.getOptions().entrySet()) {
        String key = entry.getKey();
        Map<Environment, List<String>> environments = entry.getValue();
        for (Environment environment : environments.keySet()) {
            List<String> values = environments.get(environment);
            if (values.size() == 1)
                ctx.put(key, values.get(0));
            else
                ctx.put(key, values.toArray(new String[values.size()]));
        }
    }

    // Did we find something?

    QuartzJob job = new QuartzJob(identifier, c, ctx, jobTrigger);
    job.options = options;

    // name
    String name = XPathHelper.valueOf(config, "m:name", xPathProcessor);
    job.setName(name);

    return job;
}

From source file:com.stratio.deep.es.utils.UtilES.java

/**
 * converts from JSONObject to an entity class with deep's anotations
 *
 * @param classEntity the entity name.//from  w  w  w  . j  av  a2  s  .co m
 * @param jsonObject  the instance of the JSONObject to convert.
 * @param <T>         return type.
 * @return the provided JSONObject converted to an instance of T.
 * @throws IllegalAccessException
 * @throws InstantiationException
 * @throws java.lang.reflect.InvocationTargetException
 */
public static <T> T getObjectFromJson(Class<T> classEntity, LinkedMapWritable jsonObject)
        throws IllegalAccessException, InstantiationException, InvocationTargetException,
        NoSuchMethodException {
    T t = classEntity.newInstance();

    Field[] fields = AnnotationUtils.filterDeepFields(classEntity);

    Object insert;

    for (Field field : fields) {
        Method method = Utils.findSetter(field.getName(), classEntity, field.getType());

        Class<?> classField = field.getType();
        String key = AnnotationUtils.deepFieldName(field);
        Text text = new org.apache.hadoop.io.Text(key);
        Writable currentJson = jsonObject.get(text);
        if (currentJson != null) {

            if (Iterable.class.isAssignableFrom(classField)) {
                Type type = field.getGenericType();
                insert = subDocumentListCase(type, (ArrayWritable) currentJson);
                method.invoke(t, (insert));

            } else if (IDeepType.class.isAssignableFrom(classField)) {
                insert = getObjectFromJson(classField, (LinkedMapWritable) currentJson);
                method.invoke(t, (insert));
            } else {
                insert = currentJson;
                try {
                    method.invoke(t, getObjectFromWritable((Writable) insert));
                } catch (Exception e) {
                    LOG.error("impossible to convert field " + t + " :" + field + " error: " + e.getMessage());
                    method.invoke(t,
                            Utils.castNumberType(getObjectFromWritable((Writable) insert), t.getClass()));
                }

            }

        }
    }

    return t;
}

From source file:com.formkiq.core.form.bean.ObjectBuilder.java

/**
 * Transforms a {@link FormJSON} to a {@link List}.
 * @param <T> Type of object/*from   www  .j  av a  2s  . co m*/
 * @param form {@link FormJSON}
 * @param clazz {@link Class}
 * @return {@link List}
 */
public static <T> List<T> toObject(final FormJSON form, final Class<T> clazz) {

    try {

        List<T> list = new ArrayList<>();
        BeanUtilsBean bbean = getBeanUtils();

        for (FormJSONSection section : form.getSections()) {

            T bean = clazz.newInstance();
            list.add(bean);

            for (FormJSONField f : section.getFields()) {
                if (!isEmpty(f.getValuekey())) {
                    bbean.setProperty(bean, f.getValuekey(), f.getValue());
                }
            }

            updateFieldIfNullAndExists(bbean, bean, "insertedDate", new Date());
            updateFieldIfNullAndExists(bbean, bean, "updatedDate", new Date());
        }

        return list;

    } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
        throw new RuntimeException(e);
    }
}

From source file:Main.java

@SuppressWarnings("unchecked")
public static <T extends Fragment> T attach(Activity activity, int containerId, Class<T> fragmentType,
        String tag) {/*from w w w . j a va2 s . c  om*/
    if (activity == null) {
        throw new IllegalArgumentException("activity is null");
    }
    if (fragmentType == null) {
        throw new IllegalArgumentException("fragmentType is null");
    }
    if (tag == null) {
        throw new IllegalArgumentException("tag is null");
    }

    T result;

    FragmentManager manager = activity.getFragmentManager();
    Fragment fragment = manager.findFragmentByTag(tag);

    if (fragment == null) {
        try {
            result = fragmentType.newInstance();
        } catch (InstantiationException e) {
            throw new IllegalArgumentException(
                    "fragmentType cannot be instantiated (default constructor is not visible)", e);
        } catch (IllegalAccessException e) {
            throw new IllegalArgumentException(
                    "fragmentType cannot be instantiated (instance could not be created)", e);
        }

        manager.beginTransaction().add(containerId, result, tag).commit();
    } else {
        if (!fragmentType.isInstance(fragment)) {
            throw new IllegalArgumentException("Different fragmentType for tag");
        }

        result = (T) fragment;
    }

    return result;
}