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:net.servicefixture.util.ReflectionUtils.java

/**
 * Helper method to create a new instance of a class. Throws
 * FixtureException if anything goes wrong.
 */// ww w .  j  a  v a  2  s.  c  o  m
public static Object newInstance(Class clazz) {
    try {
        return clazz.newInstance();
    } catch (Exception e) {
        throw new ServiceFixtureException("Unable to create the new instance of class:" + clazz.getName(), e);
    }
}

From source file:org.zht.framework.util.ZBeanUtil.java

@SuppressWarnings("rawtypes")
public static Object convertMapToBean(Map map, Class<?> type) {
    Object obj = null;/*  w w w.j ava 2  s . c o m*/
    try {
        BeanInfo beanInfo = null;

        beanInfo = Introspector.getBeanInfo(type);
        obj = type.newInstance();
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
        for (PropertyDescriptor property : propertyDescriptors) {
            String properName = property.getName();
            if (map.containsKey(property.getName())) {
                try {// ??

                    Object value = map.get(properName);
                    Method setter = property.getWriteMethod();
                    setter.invoke(obj, value);
                    //Unable to find non-private method
                    //               access.invoke(obj,"set" + ZStrUtil.toUpCaseFirst(properName),value);
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        return obj;
    }
    return obj;
}

From source file:com.threewks.thundr.module.Modules.java

protected static Module loadModule(Class<? extends Module> moduleClass) {
    try {/*from  w  w  w  .  j  a v a  2  s .  c  o  m*/
        Object newInstance = moduleClass.newInstance();
        Module configuration = Cast.as(newInstance, Module.class);
        if (configuration == null) {
            throw new ModuleLoadingException(
                    "Failed to load module '%s' - the configuration class %s does not implement '%s'",
                    moduleClass.getName(), Module.class.getName());
        }
        return configuration;
    } catch (InstantiationException e) {
        throw new ModuleLoadingException(e, moduleClass.getPackage().getName(),
                "failed to instantiate configuration class %s: %s", moduleClass.getName(), e.getMessage());
    } catch (IllegalAccessException e) {
        throw new ModuleLoadingException(e, moduleClass.getPackage().getName(),
                "cannot instantiate configuration class %s: %s", moduleClass.getName(), e.getMessage());
    }
}

From source file:com.digitalpebble.storm.crawler.persistence.Scheduler.java

/** Returns a Scheduler instance based on the configuration **/
@SuppressWarnings({ "rawtypes", "unchecked" })
public static Scheduler getInstance(Map stormConf) {
    Scheduler scheduler;// w w w  .  j av  a 2  s.c  o  m

    String className = ConfUtils.getString(stormConf, schedulerClassParamName);

    if (StringUtils.isBlank(className)) {
        throw new RuntimeException("Missing value for config  " + schedulerClassParamName);
    }

    try {
        Class<?> schedulerc = Class.forName(className);
        boolean interfaceOK = Scheduler.class.isAssignableFrom(schedulerc);
        if (!interfaceOK) {
            throw new RuntimeException("Class " + className + " must extend Scheduler");
        }
        scheduler = (Scheduler) schedulerc.newInstance();
    } catch (Exception e) {
        throw new RuntimeException("Can't instanciate " + className);
    }

    scheduler.init(stormConf);
    return scheduler;
}

From source file:com.netsteadfast.greenstep.bsc.util.WorkspaceUtils.java

private static String getCompomentRenderBody(WorkspaceCompomentVO compoment,
        Map<String, Object> templateParameters) throws Exception {
    Class<BaseWorkspaceCompoment> clazz = (Class<BaseWorkspaceCompoment>) Class
            .forName(compoment.getClassName());
    BaseWorkspaceCompoment compomentObj = clazz.newInstance();
    compomentObj.loadFromId(compoment.getCompId());
    compomentObj.getParameters().putAll(templateParameters);
    compomentObj.doRender();//ww w.jav a  2s.  c  o m
    return StringUtils.defaultString(compomentObj.getBody());
}

From source file:com.yahoo.bard.webservice.util.Utils.java

/**
 * A recursive call to make a collection and all it's values immutable.
 *
 * @param <T>  The type of the collection
 * @param mutableCollection  The original, potentially mutable, collection
 *
 * @return Am immutable copy whose values are also immutable.
 *///from  w  w w.  j  a  va  2s. c  o m
public static <T> Collection<T> makeImmutable(Collection<T> mutableCollection) {
    Collection<T> newCollection;
    try {
        @SuppressWarnings("unchecked")
        Class<Collection<T>> cls = (Class<Collection<T>>) mutableCollection.getClass();
        newCollection = cls.newInstance();
    } catch (InstantiationException | IllegalAccessException e) {
        throw new IllegalStateException(e);
    }
    for (T element : mutableCollection) {
        newCollection.add(Utils.makeImmutable(element));
    }
    return Collections.unmodifiableCollection(newCollection);
}

From source file:com.aliyun.odps.graph.local.utils.LocalGraphRunUtils.java

@SuppressWarnings("rawtypes")
public static List<Aggregator> getAggregator(JobConf conf) {
    String classes = conf.get(GRAPH_CONF.AGGREGATOR_CLASSES);
    try {/*from w  w  w .j  a v a 2  s  .c om*/
        List<Aggregator> ret = new ArrayList<Aggregator>();
        if (classes != null) {
            String[] classNames = classes.split(";");
            for (String className : classNames) {
                if (!StringUtils.isEmpty(className)) {
                    Class c = Class.forName(className);
                    Aggregator aggr = (Aggregator) c.newInstance();
                    ret.add(aggr);
                }
            }
        }
        return ret;
    } catch (Exception e) {
        System.err.println(com.aliyun.odps.utils.StringUtils.stringifyException(e));
        List<Aggregator> ret = new ArrayList<Aggregator>();
        return ret;
    }
}

From source file:com.glaf.core.util.ClassUtils.java

public static Object instantiateObject(String className, ClassLoader classLoader) {
    Class<?> cls = ClassUtils.cache.get(className);
    if (cls == null) {
        cls = loadClass(className, classLoader);
    }// w w w  .  j  av  a  2 s  . c  o  m
    Object object = null;
    if (cls != null) {
        try {
            object = cls.newInstance();
        } catch (Throwable e) {
            throw new RuntimeException("Unable to instantiate object for class '" + className + "'", e);
        }
    }
    return object;
}

From source file:com.vk.sdk.util.VKJsonHelper.java

public static Object toArray(JSONArray array, Class arrayClass) {
    Object ret = Array.newInstance(arrayClass.getComponentType(), array.length());
    Class<?> subType = arrayClass.getComponentType();

    for (int i = 0; i < array.length(); i++) {
        try {//from  w w w.  j a  va2  s. co m
            Object jsonItem = array.get(i);
            Object objItem = subType.newInstance();
            if (jsonItem instanceof JSONObject) {
                JSONObject jsonItem2 = (JSONObject) jsonItem;
                if (objItem instanceof VKApiModel) {
                    VKApiModel objItem2 = (VKApiModel) objItem;
                    ((VKApiModel) objItem).parse(jsonItem2);
                    Array.set(ret, i, objItem2);
                }
            }
        } catch (JSONException e) {
            if (VKSdk.DEBUG)
                e.printStackTrace();
        } catch (InstantiationException e) {
            if (VKSdk.DEBUG)
                e.printStackTrace();
        } catch (IllegalAccessException e) {
            if (VKSdk.DEBUG)
                e.printStackTrace();
        }
    }
    return ret;
}

From source file:com.jaeksoft.searchlib.analysis.ClassFactory.java

/**
 * /*from www.  j  a  v a 2  s. com*/
 * @param config
 * @param factoryClass
 * @return
 * @throws SearchLibException
 */
protected static <T extends ClassFactory> T createInstance(Config config, Class<T> factoryClass)
        throws SearchLibException {
    try {
        T o = factoryClass.newInstance();
        o.setParams(config, factoryClass.getPackage().getName(), factoryClass.getSimpleName());
        o.initProperties();
        return o;
    } catch (InstantiationException e) {
        throw new SearchLibException(e);
    } catch (IllegalAccessException e) {
        throw new SearchLibException(e);
    } catch (IOException e) {
        throw new SearchLibException(e);
    }
}