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.sqewd.open.dal.core.persistence.db.EntityHelper.java

@SuppressWarnings({ "unchecked", "rawtypes" })
public static void setColumnValue(final ResultSet rs, final StructAttributeReflect attr,
        final AbstractEntity entity, final AbstractJoinGraph gr, final Stack<KeyValuePair<Class<?>>> path)
        throws Exception {

    KeyValuePair<String> alias = gr.getAliasFor(path, attr.Column, 0);
    String tabprefix = alias.getKey();

    if (EnumPrimitives.isPrimitiveType(attr.Field.getType())) {
        EnumPrimitives prim = EnumPrimitives.type(attr.Field.getType());
        switch (prim) {
        case ECharacter:
            String sv = rs.getString(tabprefix + "." + attr.Column);
            if (!rs.wasNull()) {
                PropertyUtils.setSimpleProperty(entity, attr.Field.getName(), sv.charAt(0));
            }// www  .  ja  v a  2 s .c om
            break;
        case EShort:
            short shv = rs.getShort(tabprefix + "." + attr.Column);
            if (!rs.wasNull()) {
                PropertyUtils.setSimpleProperty(entity, attr.Field.getName(), shv);
            }
            break;
        case EInteger:
            int iv = rs.getInt(tabprefix + "." + attr.Column);
            if (!rs.wasNull()) {
                PropertyUtils.setSimpleProperty(entity, attr.Field.getName(), iv);
            }
            break;
        case ELong:
            long lv = rs.getLong(tabprefix + "." + attr.Column);
            if (!rs.wasNull()) {
                PropertyUtils.setSimpleProperty(entity, attr.Field.getName(), lv);
            }
            break;
        case EFloat:
            float fv = rs.getFloat(tabprefix + "." + attr.Column);
            if (!rs.wasNull()) {
                PropertyUtils.setSimpleProperty(entity, attr.Field.getName(), fv);
            }
            break;
        case EDouble:
            double dv = rs.getDouble(tabprefix + "." + attr.Column);
            if (!rs.wasNull()) {
                PropertyUtils.setSimpleProperty(entity, attr.Field.getName(), dv);
            }
            break;
        default:
            throw new Exception("Unsupported Data type [" + prim.name() + "]");
        }
    } else if (attr.Convertor != null) {
        String value = rs.getString(tabprefix + "." + attr.Column);
        if (!rs.wasNull()) {
            attr.Convertor.load(entity, attr.Column, value);
        }
    } else if (attr.Field.getType().equals(String.class)) {
        String value = rs.getString(tabprefix + "." + attr.Column);
        if (!rs.wasNull()) {
            PropertyUtils.setSimpleProperty(entity, attr.Field.getName(), value);
        }
    } else if (attr.Field.getType().equals(Date.class)) {
        long value = rs.getLong(tabprefix + "." + attr.Column);
        if (!rs.wasNull()) {
            Date dt = new Date(value);
            PropertyUtils.setSimpleProperty(entity, attr.Field.getName(), dt);
        }
    } else if (attr.Field.getType().isEnum()) {
        String value = rs.getString(tabprefix + "." + attr.Column);
        if (!rs.wasNull()) {
            Class ecls = attr.Field.getType();
            Object evalue = Enum.valueOf(ecls, value);
            PropertyUtils.setSimpleProperty(entity, attr.Field.getName(), evalue);
        }
    } else if (attr.Reference != null) {
        Class<?> rt = Class.forName(attr.Reference.Class);
        Object obj = rt.newInstance();
        if (!(obj instanceof AbstractEntity))
            throw new Exception("Unsupported Entity type [" + rt.getCanonicalName() + "]");
        AbstractEntity rentity = (AbstractEntity) obj;
        if (path.size() > 0) {
            path.peek().setKey(attr.Column);
        }

        KeyValuePair<Class<?>> cls = new KeyValuePair<Class<?>>();
        cls.setValue(rentity.getClass());
        path.push(cls);
        setEntity(rentity, rs, gr, path);
        PropertyUtils.setSimpleProperty(entity, attr.Field.getName(), rentity);
        path.pop();
    }
}

From source file:com.asakusafw.testdriver.tools.runner.BatchTestTruncator.java

private static void resolveBatch(Conf conf, Class<? extends BatchDescription> aClass) {
    LOG.debug("analyzing batch: {}", aClass.getName()); //$NON-NLS-1$
    List<Class<? extends FlowDescription>> flows = new ArrayList<>();
    try {// w  w w  .j  a v a 2  s.  c o m
        BatchDescription batch = aClass.newInstance();
        batch.start();
        for (Work work : batch.getWorks()) {
            WorkDescription desc = work.getDescription();
            if (desc instanceof JobFlowWorkDescription) {
                Class<? extends FlowDescription> flow = ((JobFlowWorkDescription) desc).getFlowClass();
                flows.add(flow);
            }
        }
    } catch (ReflectiveOperationException e) {
        throw new IllegalArgumentException(
                MessageFormat.format(Messages.getString("BatchTestTruncator.errorInvalidBatchClass"), //$NON-NLS-1$
                        aClass.getName()));
    }
    for (Class<? extends FlowDescription> flow : flows) {
        resolveFlow(conf, flow);
    }
}

From source file:com.ixcode.framework.model.lookup.LookupHandler.java

private static IPagedQuery instantiateQuery(Class serverQueryClass,
        IServerQueryParameters serverQueryParameters, int serverPageSize, int displayPageSize)
        throws ServletException {
    try {/*from  www .  j  av  a2  s .c o m*/
        IServerQuery serverQuery = (IServerQuery) serverQueryClass.newInstance();
        return new PagedQuery(serverQuery, serverPageSize, displayPageSize, serverQueryParameters);
    } catch (IllegalAccessException e) {
        throw new ServletExceptionWrapper(e);
    } catch (InstantiationException e) {
        throw new ServletExceptionWrapper(e);
    }
}

From source file:com.sqewd.open.dal.core.persistence.db.EntityHelper.java

@SuppressWarnings({ "rawtypes", "unchecked" })
public static Object getColumnValue(final ResultSet rs, final StructAttributeReflect attr,
        final AbstractEntity entity, final AbstractJoinGraph gr, final Stack<KeyValuePair<Class<?>>> path)
        throws Exception {

    Object value = null;//from  w w w  .  j  ava  2 s. c o m

    KeyValuePair<String> alias = gr.getAliasFor(path, attr.Column, 0);
    String tabprefix = alias.getKey();

    if (EnumPrimitives.isPrimitiveType(attr.Field.getType())) {
        EnumPrimitives prim = EnumPrimitives.type(attr.Field.getType());
        switch (prim) {
        case ECharacter:
            String sv = rs.getString(tabprefix + "." + attr.Column);
            if (!rs.wasNull()) {
                PropertyUtils.setSimpleProperty(entity, attr.Field.getName(), sv.charAt(0));
            }
            break;
        case EShort:
            short shv = rs.getShort(tabprefix + "." + attr.Column);
            if (!rs.wasNull()) {
                PropertyUtils.setSimpleProperty(entity, attr.Field.getName(), shv);
            }
            break;
        case EInteger:
            int iv = rs.getInt(tabprefix + "." + attr.Column);
            if (!rs.wasNull()) {
                PropertyUtils.setSimpleProperty(entity, attr.Field.getName(), iv);
            }
            break;
        case ELong:
            long lv = rs.getLong(tabprefix + "." + attr.Column);
            if (!rs.wasNull()) {
                PropertyUtils.setSimpleProperty(entity, attr.Field.getName(), lv);
            }
            break;
        case EFloat:
            float fv = rs.getFloat(tabprefix + "." + attr.Column);
            if (!rs.wasNull()) {
                PropertyUtils.setSimpleProperty(entity, attr.Field.getName(), fv);
            }
            break;
        case EDouble:
            double dv = rs.getDouble(tabprefix + "." + attr.Column);
            if (!rs.wasNull()) {
                PropertyUtils.setSimpleProperty(entity, attr.Field.getName(), dv);
            }
            break;
        default:
            throw new Exception("Unsupported Data type [" + prim.name() + "]");
        }
    } else if (attr.Convertor != null) {
        // TODO : Not supported at this time.
        value = rs.getString(tabprefix + "." + attr.Column);

    } else if (attr.Field.getType().equals(String.class)) {
        value = rs.getString(tabprefix + "." + attr.Column);
        if (rs.wasNull()) {
            value = null;
        }
    } else if (attr.Field.getType().equals(Date.class)) {
        long lvalue = rs.getLong(tabprefix + "." + attr.Column);
        if (!rs.wasNull()) {
            Date dt = new Date(lvalue);
            value = dt;
        }
    } else if (attr.Field.getType().isEnum()) {
        String svalue = rs.getString(tabprefix + "." + attr.Column);
        if (!rs.wasNull()) {
            Class ecls = attr.Field.getType();
            value = Enum.valueOf(ecls, svalue);
        }
    } else if (attr.Reference != null) {
        Class<?> rt = Class.forName(attr.Reference.Class);
        Object obj = rt.newInstance();
        if (!(obj instanceof AbstractEntity))
            throw new Exception("Unsupported Entity type [" + rt.getCanonicalName() + "]");
        AbstractEntity rentity = (AbstractEntity) obj;
        if (path.size() > 0) {
            path.peek().setKey(attr.Column);
        }

        KeyValuePair<Class<?>> cls = new KeyValuePair<Class<?>>();
        cls.setValue(rentity.getClass());
        path.push(cls);
        setEntity(rentity, rs, gr, path);
        value = rentity;
        path.pop();
    }
    return value;
}

From source file:com.mmj.app.lucene.solr.client.SolrClient.java

public static Object toBean(SolrDocument record, Class<?> clazz) {

    Object o = null;//from  w w  w.ja  v  a2 s. c om
    try {
        o = clazz.newInstance();
    } catch (InstantiationException e1) {
        e1.printStackTrace();
    } catch (IllegalAccessException e1) {
        e1.printStackTrace();
    }
    Field[] fields = clazz.getDeclaredFields();
    for (Field field : fields) {
        Object value = record.get(field.getName());
        ConvertUtils.register(new DateConverter(null), java.util.Date.class);
        try {
            BeanUtils.setProperty(o, field.getName(), value);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
    return o;
}

From source file:com.jhkt.playgroundArena.db.nosql.mongodb.beans.AbstractDocument.java

private final static Object convertBacktoClassInstanceHelper(DBObject dBObject) {

    Object returnValue = null;// w ww . ja va2s  . c  o  m

    try {
        String className = dBObject.get(JPAConstants.CONVERTER_CLASS.CLASS.name()).toString();
        Class<?> classCheck = Class.forName(className);

        if (AbstractDocument.class.isAssignableFrom(classCheck)) {
            Class<? extends AbstractDocument> classToConvertTo = classCheck.asSubclass(AbstractDocument.class);
            AbstractDocument dInstance = classToConvertTo.newInstance();

            for (String key : dBObject.keySet()) {
                Object value = dBObject.get(key);

                char[] propertyChars = key.toCharArray();
                String methodMain = String.valueOf(propertyChars[0]).toUpperCase() + key.substring(1);
                String methodName = "set" + methodMain;
                String getMethodName = "get" + methodMain;

                if (key.equals(JPAConstants.CONVERTER_CLASS.CLASS.name())) {
                    continue;
                }

                if (value instanceof BasicDBObject) {
                    value = convertBacktoClassInstanceHelper(BasicDBObject.class.cast(value));
                }

                try {
                    Method getMethod = classToConvertTo.getMethod(getMethodName);
                    Class<?> getReturnType = getMethod.getReturnType();
                    Method method = classToConvertTo.getMethod(methodName, getReturnType);

                    if (getMethod.isAnnotationPresent(IDocumentKeyValue.class)) {
                        method.invoke(dInstance, value);
                    }
                } catch (NoSuchMethodException nsMe) {
                    _log.warn("Within convertBacktoClassInstance, following method was not found " + methodName,
                            nsMe);
                }

            }

            returnValue = dInstance;

        } else if (Enum.class.isAssignableFrom(classCheck)) {

            List<?> constants = Arrays.asList(classCheck.getEnumConstants());
            String name = String.class.cast(dBObject.get(JPAConstants.CONVERTER_CLASS.CONTENT.name()));
            for (Object constant : constants) {
                if (constant.toString().equals(name)) {
                    returnValue = constant;
                }
            }

        } else if (Collection.class.isAssignableFrom(classCheck)) {

            @SuppressWarnings("unchecked")
            Class<? extends Collection<? super Object>> classToConvertTo = (Class<? extends Collection<? super Object>>) classCheck;
            Collection<? super Object> cInstance = classToConvertTo.newInstance();

            BasicDBList bDBList = (BasicDBList) dBObject.get(JPAConstants.CONVERTER_CLASS.CONTENT.name());
            cInstance.addAll(bDBList);

            returnValue = cInstance;

        } else if (Map.class.isAssignableFrom(classCheck)) {

            @SuppressWarnings("unchecked")
            Class<? extends Map<String, ? super Object>> classToConvertTo = (Class<? extends Map<String, ? super Object>>) classCheck;
            Map<String, ? super Object> mInstance = classToConvertTo.newInstance();

            BasicDBObject mapObject = (BasicDBObject) dBObject.get(JPAConstants.CONVERTER_CLASS.CONTENT.name());
            mInstance.putAll(mapObject);

            returnValue = mInstance;

        }

    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    return returnValue;
}

From source file:org.codehaus.griffon.runtime.spring.GriffonRuntimeConfigurator.java

public static BeanBuilder reloadSpringResourcesConfig(GriffonApplication application, BeanBuilder beanBuilder,
        Class<?> groovySpringResourcesClass) throws InstantiationException, IllegalAccessException {
    beanBuilder.setBinding(new Binding(CollectionUtils.newMap("application", application)));
    Script script = (Script) groovySpringResourcesClass.newInstance();
    script.run();/*from   ww w.  j  av  a  2s . c  om*/
    Object beans = script.getProperty("beans");
    beanBuilder.beans((Closure<?>) beans);
    return beanBuilder;
}

From source file:edu.vt.middleware.gator.log4j.Log4jConfigUtils.java

/**
 * Instantiate a new instance of the given class name.
 *
 * @param  <T>  Type of class to instantiate.
 * @param  clazz  Class of type to instantiate.
 * @param  name  Fully-qualified class name.
 *
 * @return  New instance of specified class.
 *
 * @throws  ConfigurationException  On configuration errors.
 *///from w ww  .j  a v a 2 s  .c  o  m
public static <T> T instantiate(final Class<T> clazz, final String name) throws ConfigurationException {
    Class<?> c;
    try {
        LOGGER.trace("Instantiating new instance of " + name);
        c = Class.forName(name);
    } catch (ClassNotFoundException e) {
        throw new ConfigurationException(String.format("Class %s not found.", name));
    }
    try {
        return clazz.cast(c.newInstance());
    } catch (InstantiationException e) {
        throw new ConfigurationException(String.format("Cannot instantiate %s.", name), e);
    } catch (IllegalAccessException e) {
        throw new ConfigurationException(
                String.format("Cannot instantiate %s -- constructor not accessible.", name), e);
    } catch (ClassCastException e) {
        throw new ConfigurationException(String.format("%s is not an instance of %s", name, clazz), e);
    }
}

From source file:com.linkedin.pinot.routing.RoutingTableSelectorFactory.java

public static RoutingTableSelector getRoutingTableSelector(Configuration config) {
    RoutingTableSelector routingTableSelector = new PercentageBasedRoutingTableSelector();
    if (config == null) {
        LOGGER.warn("No config for routing table selector. Using default");
    } else {/*ww w. ja  v  a  2  s . co  m*/
        String selectorClassName = null;
        try {
            selectorClassName = (String) config.getProperty(CLASSNAME_KEY);
        } catch (Exception e) {
            LOGGER.warn("Could not parse property '{}'. Using {}", CLASSNAME_KEY, defaultClasssName, e);
        }

        Class<? extends RoutingTableSelector> clazz;
        if (selectorClassName == null || selectorClassName.isEmpty()) {
            LOGGER.info("Null or empty selector class name. Using default");
        } else {
            try {
                clazz = (Class<? extends RoutingTableSelector>) Class.forName(selectorClassName);
                routingTableSelector = clazz.newInstance();
            } catch (ClassNotFoundException e) {
                LOGGER.warn("Could not load '{}'. Loading {}", selectorClassName, defaultClasssName, e);
            } catch (InstantiationException e) {
                LOGGER.warn("Could not instantiate '{}'. Instantiating {}", selectorClassName,
                        defaultClasssName, e);
            } catch (IllegalAccessException e) {
                LOGGER.warn("Could not instantiate '{}'. Instantiating {}", selectorClassName,
                        defaultClasssName, e);
            }
        }
    }

    routingTableSelector.init(config);

    return routingTableSelector;
}

From source file:com.springframework.core.io.support.SpringFactoriesLoader.java

@SuppressWarnings("unchecked")
private static <T> T instantiateFactory(String instanceClassName, Class<T> factoryClass,
        ClassLoader classLoader) {
    try {//ww  w  .j  a  v  a2 s  .  c o m
        Class<?> instanceClass = ClassUtils.forName(instanceClassName, classLoader);
        if (!factoryClass.isAssignableFrom(instanceClass)) {
            throw new IllegalArgumentException(
                    "Class [" + instanceClassName + "] is not assignable to [" + factoryClass.getName() + "]");
        }
        return (T) instanceClass.newInstance();
    } catch (Throwable ex) {
        throw new IllegalArgumentException("Cannot instantiate factory class: " + factoryClass.getName(), ex);
    }
}