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.tc.util.factory.AbstractFactory.java

public static AbstractFactory getFactory(String id, Class<?> defaultImpl) {
    String factoryClassName = findFactoryClassName(id);
    AbstractFactory factory = null;/* w w w  . j a v  a 2 s  .  c  o  m*/

    if (factoryClassName != null) {
        try {
            factory = (AbstractFactory) Class.forName(factoryClassName).newInstance();
        } catch (Exception e) {
            throw new RuntimeException("Could not instantiate '" + factoryClassName + "'", e);
        }
    }

    if (factory == null) {
        try {
            factory = (AbstractFactory) defaultImpl.newInstance();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    return factory;
}

From source file:com.bosscs.spark.commons.utils.Utils.java

/**
 * Creates a new instance of the given class name.
 *
 * @param <T>         the type parameter
 * @param className   the class object for which a new instance should be created.
 * @param returnClass the return class/*from   w ww.j  av  a2 s.  c o m*/
 * @return the new instance of class clazz.
 */
@SuppressWarnings("unchecked")
public static <T> T newTypeInstance(String className, Class<T> returnClass) {
    try {
        Class<T> clazz = (Class<T>) Class.forName(className);
        return clazz.newInstance();
    } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
        throw new GenericException(e);
    }
}

From source file:com.icesoft.faces.component.util.CustomComponentUtils.java

public static Object newInstance(Class clazz) throws FacesException {
    try {/*from  ww  w  .jav  a2  s  .c o m*/
        return clazz.newInstance();
    } catch (NoClassDefFoundError e) {
        throw new FacesException(e);
    } catch (InstantiationException e) {
        throw new FacesException(e);
    } catch (IllegalAccessException e) {
        throw new FacesException(e);
    }
}

From source file:com.stratio.deep.commons.utils.Utils.java

/**
 * Creates a new instance of the given class name.
 *
 * @param <T>         the type parameter
 * @param className   the class object for which a new instance should be created.
 * @param returnClass the return class//  w w w. j a va2 s  . c om
 * @return the new instance of class clazz.
 */
@SuppressWarnings("unchecked")
public static <T> T newTypeInstance(String className, Class<T> returnClass) {
    try {
        Class<T> clazz = (Class<T>) Class.forName(className);
        return clazz.newInstance();
    } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
        throw new DeepGenericException(e);
    }
}

From source file:com.espertech.esper.util.PopulateUtil.java

public static Object instantiatePopulateObject(Map<String, Object> objectProperties, Class topClass,
        EngineImportService engineImportService) throws ExprValidationException {

    Class applicableClass = topClass;
    if (topClass.isInterface()) {
        applicableClass = findInterfaceImplementation(objectProperties, topClass, engineImportService);
    }/* w w w  . ja v a 2  s. c o  m*/

    Object top;
    try {
        top = applicableClass.newInstance();
    } catch (RuntimeException e) {
        throw new ExprValidationException(
                "Exception instantiating class " + applicableClass.getName() + ": " + e.getMessage(), e);
    } catch (InstantiationException e) {
        throw new ExprValidationException(getMessageExceptionInstantiating(applicableClass), e);
    } catch (IllegalAccessException e) {
        throw new ExprValidationException(
                "Illegal access to construct class " + applicableClass.getName() + ": " + e.getMessage(), e);
    }

    populateObject(topClass.getSimpleName(), 0, topClass.getSimpleName(), objectProperties, top,
            engineImportService, null, null);

    return top;
}

From source file:com.microsoft.services.sharepoint.OfficeEntity.java

/**
 * List from json.//from   ww w  .j  a v a2 s.c  om
 * 
 * @param <E>
 *            the element type
 * @param json
 *            the json
 * @param clazz
 *            the clazz
 * @return the list
 * @throws org.json.JSONException
 *             the JSON exception
 */
protected static <E extends OfficeEntity> List<E> listFromJson(JSONObject json, Class<E> clazz)
        throws JSONException {
    List<E> list = new ArrayList<E>();

    JSONArray results;
    if (json.has("d")) {
        results = json.getJSONObject("d").getJSONArray("results");
    } else {
        results = json.getJSONArray("results");
    }

    for (int i = 0; i < results.length(); i++) {
        JSONObject result = results.getJSONObject(i);

        E item = null;
        try {
            item = clazz.newInstance();
        } catch (Throwable e) {
        }

        if (item != null) {
            item.loadFromJson(result);
            list.add(item);
        }
    }

    return list;
}

From source file:io.apiman.manager.api.es.EsMarshallingTest.java

/**
 * Fabricates a new instance of the given bean type.  Uses reflection to figure
 * out all the fields and assign generated values for each.
 *///from  ww  w. j ava2  s.  co m
private static <T> T createBean(Class<T> beanClass) throws InstantiationException, IllegalAccessException,
        InvocationTargetException, NoSuchMethodException, SecurityException, ClassNotFoundException {
    T bean = beanClass.newInstance();
    Map<String, String> beanProps = BeanUtils.describe(bean);
    for (String key : beanProps.keySet()) {
        try {
            Field declaredField = beanClass.getDeclaredField(key);
            Class<?> fieldType = declaredField.getType();
            if (fieldType == String.class) {
                BeanUtils.setProperty(bean, key, StringUtils.upperCase(key));
            } else if (fieldType == Boolean.class || fieldType == boolean.class) {
                BeanUtils.setProperty(bean, key, Boolean.TRUE);
            } else if (fieldType == Date.class) {
                BeanUtils.setProperty(bean, key, new Date(1));
            } else if (fieldType == Long.class || fieldType == long.class) {
                BeanUtils.setProperty(bean, key, 17L);
            } else if (fieldType == Integer.class || fieldType == long.class) {
                BeanUtils.setProperty(bean, key, 11);
            } else if (fieldType == Set.class) {
                // Initialize to a linked hash set so that order is maintained.
                BeanUtils.setProperty(bean, key, new LinkedHashSet());

                Type genericType = declaredField.getGenericType();
                String typeName = genericType.getTypeName();
                String typeClassName = typeName.substring(14, typeName.length() - 1);
                Class<?> typeClass = Class.forName(typeClassName);
                Set collection = (Set) BeanUtilsBean.getInstance().getPropertyUtils().getProperty(bean, key);
                populateSet(collection, typeClass);
            } else if (fieldType == Map.class) {
                Map<String, String> map = new LinkedHashMap<String, String>();
                map.put("KEY-1", "VALUE-1");
                map.put("KEY-2", "VALUE-2");
                BeanUtils.setProperty(bean, key, map);
            } else if (fieldType.isEnum()) {
                BeanUtils.setProperty(bean, key, fieldType.getEnumConstants()[0]);
            } else if (fieldType.getPackage() != null
                    && fieldType.getPackage().getName().startsWith("io.apiman.manager.api.beans")) {
                Object childBean = createBean(fieldType);
                BeanUtils.setProperty(bean, key, childBean);
            } else {
                throw new IllegalAccessException(
                        "Failed to handle property named [" + key + "] type: " + fieldType.getSimpleName());
            }
            //            String capKey = StringUtils.capitalize(key);
            //            System.out.println(key);;
        } catch (NoSuchFieldException e) {
            // Skip it - there is not really a bean property with this name!
        }
    }
    return bean;
}

From source file:info.novatec.testit.livingdoc.util.ClassUtils.java

public static <C> C createInstanceFromClassNameWithArguments(ClassLoader classLoader, String classWithArguments,
        Class<C> expectedType) throws UndeclaredThrowableException {
    try {// w  w  w .  j a v a 2 s  .  c o  m
        List<String> parameters = toList(escapeValues(classWithArguments.split(";")));
        Class<?> klass = ClassUtils.loadClass(classLoader, shift(parameters));

        if (!expectedType.isAssignableFrom(klass)) {
            throw new IllegalArgumentException(
                    "Class " + expectedType.getName() + " is not assignable from " + klass.getName());
        }

        if (parameters.size() == 0) {
            return expectedType.cast(klass.newInstance());
        }

        String[] args = parameters.toArray(new String[parameters.size()]);
        Constructor<?> constructor = klass.getConstructor(args.getClass());
        return expectedType.cast(constructor.newInstance(new Object[] { args }));
    } catch (ClassNotFoundException e) {
        throw new UndeclaredThrowableException(e);
    } catch (InstantiationException e) {
        throw new UndeclaredThrowableException(e);
    } catch (IllegalAccessException e) {
        throw new UndeclaredThrowableException(e);
    } catch (NoSuchMethodException e) {
        throw new UndeclaredThrowableException(e);
    } catch (InvocationTargetException e) {
        throw new UndeclaredThrowableException(e);
    }
}

From source file:com.haulmont.cuba.core.sys.persistence.DbmsSpecificFactory.java

public static <T> T create(Class<T> intf, String dbmsType, String dbmsVersion) {
    String intfName = intf.getName();
    String packageName = intfName.substring(0, intfName.lastIndexOf('.') + 1);

    String name = packageName + StringUtils.capitalize(dbmsType) + dbmsVersion + intf.getSimpleName();
    Class<?> aClass;
    try {//from  w w  w.  java2 s. com
        aClass = ReflectionHelper.loadClass(name);
    } catch (ClassNotFoundException e) {
        name = packageName + StringUtils.capitalize(dbmsType) + intf.getSimpleName();
        try {
            aClass = ReflectionHelper.loadClass(name);
        } catch (ClassNotFoundException e1) {
            throw new RuntimeException("Error creating " + intfName + " implementation", e1);
        }
    }
    try {
        //noinspection unchecked
        return (T) aClass.newInstance();
    } catch (InstantiationException | IllegalAccessException e) {
        throw new RuntimeException("Error creating " + intfName + " implementation", e);
    }
}

From source file:org.hellojavaer.testcase.generator.TestCaseGenerator.java

@SuppressWarnings({ "unchecked", "rawtypes" })
private static <T> T produceBean(Class<T> clazz, ControlParam countrolParam, Stack<Class> parseClassList) {
    try {//  www . java  2 s . c o m
        T item = clazz.newInstance();
        for (PropertyDescriptor pd : BeanUtils.getPropertyDescriptors(clazz)) {
            Method writeMethod = pd.getWriteMethod();
            if (writeMethod == null || pd.getReadMethod() == null || //
                    countrolParam.getExcludeFieldList() != null
                            && countrolParam.getExcludeFieldList().contains(pd.getName())//
            ) {//
                continue;
            }
            Class fieldClazz = pd.getPropertyType();
            Long numIndex = countrolParam.getNumIndex();
            // int enumIndex = countrolParam.getEnumIndex();
            Random random = countrolParam.getRandom();
            long strIndex = countrolParam.getStrIndex();
            int charIndex = countrolParam.getCharIndex();
            Calendar time = countrolParam.getTime();
            if (TypeUtil.isBaseType(fieldClazz)) {
                if (TypeUtil.isNumberType(fieldClazz)) {
                    if (fieldClazz == Byte.class) {
                        writeMethod.invoke(item, Byte.valueOf((byte) (numIndex & 0x7F)));
                    } else if (fieldClazz == Short.class) {
                        writeMethod.invoke(item, Short.valueOf((short) (numIndex & 0x7FFF)));
                    } else if (fieldClazz == Integer.class) {
                        writeMethod.invoke(item, Integer.valueOf((int) (numIndex & 0x7FFFFFFF)));
                    } else if (fieldClazz == Long.class) {
                        writeMethod.invoke(item, Long.valueOf((long) numIndex));
                    } else if (fieldClazz == Float.class) {
                        writeMethod.invoke(item, Float.valueOf((float) numIndex));
                    } else if (fieldClazz == Double.class) {
                        writeMethod.invoke(item, Double.valueOf((double) numIndex));
                    } else if (fieldClazz == byte.class) {//
                        writeMethod.invoke(item, (byte) (numIndex & 0x7F));
                    } else if (fieldClazz == short.class) {
                        writeMethod.invoke(item, (short) (numIndex & 0x7FFF));
                    } else if (fieldClazz == int.class) {
                        writeMethod.invoke(item, (int) (numIndex & 0x7FFFFFFF));
                    } else if (fieldClazz == long.class) {
                        writeMethod.invoke(item, (long) numIndex);
                    } else if (fieldClazz == float.class) {
                        writeMethod.invoke(item, (float) numIndex);
                    } else if (fieldClazz == double.class) {
                        writeMethod.invoke(item, (double) numIndex);
                    }
                    numIndex++;
                    if (numIndex < 0) {
                        numIndex &= 0x7FFFFFFFFFFFFFFFL;
                    }
                    countrolParam.setNumIndex(numIndex);
                } else if (fieldClazz == boolean.class) {
                    writeMethod.invoke(item, random.nextBoolean());
                } else if (fieldClazz == Boolean.class) {
                    writeMethod.invoke(item, Boolean.valueOf(random.nextBoolean()));
                } else if (fieldClazz == char.class) {
                    writeMethod.invoke(item, CHAR_RANGE[charIndex]);
                    charIndex++;
                    if (charIndex >= CHAR_RANGE.length) {
                        charIndex = 0;
                    }
                    countrolParam.setCharIndex(charIndex);
                } else if (fieldClazz == Character.class) {
                    writeMethod.invoke(item, Character.valueOf(CHAR_RANGE[charIndex]));
                    charIndex++;
                    if (charIndex >= CHAR_RANGE.length) {
                        charIndex = 0;
                    }
                    countrolParam.setCharIndex(charIndex);
                } else if (fieldClazz == String.class) {
                    if (countrolParam.getUniqueFieldList() != null
                            && countrolParam.getUniqueFieldList().contains(pd.getName())) {
                        StringBuilder sb = new StringBuilder();
                        convertNum(strIndex, STRING_RANGE, countrolParam.getRandom(), sb);
                        writeMethod.invoke(item, sb.toString());
                        strIndex += countrolParam.getStrStep();
                        if (strIndex < 0) {
                            strIndex &= 0x7FFFFFFFFFFFFFFFL;
                        }
                        countrolParam.setStrIndex(strIndex);
                    } else {
                        writeMethod.invoke(item, String.valueOf(CHAR_RANGE[charIndex]));
                        charIndex++;
                        if (charIndex >= CHAR_RANGE.length) {
                            charIndex = 0;
                        }
                        countrolParam.setCharIndex(charIndex);
                    }

                } else if (fieldClazz == Date.class) {
                    writeMethod.invoke(item, time.getTime());
                    time.add(Calendar.DAY_OF_YEAR, 1);
                } else if (fieldClazz.isEnum()) {
                    int index = random.nextInt(fieldClazz.getEnumConstants().length);
                    writeMethod.invoke(item, fieldClazz.getEnumConstants()[index]);
                } else {
                    //
                    throw new RuntimeException("out of countrol Class " + fieldClazz.getName());
                }
            } else {
                parseClassList.push(fieldClazz);
                // TODO ?
                Set<Class> set = new HashSet<Class>(parseClassList);
                if (parseClassList.size() - set.size() <= countrolParam.getRecursiveCycleLimit()) {
                    Object bean = produceBean(fieldClazz, countrolParam, parseClassList);
                    writeMethod.invoke(item, bean);
                }
                parseClassList.pop();
            }
        }
        return item;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}