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.liferay.wsrp.proxy.TypeConvertorUtil.java

public static Object convert(Object source, int sourceVersion) throws Exception {

    if (source == null) {
        return null;
    }/*w  w w  . j a v a  2s.c  o  m*/

    String sourcePackage = _V1_PACKAGE;
    String destinationPackage = _V2_PACKAGE;

    if (sourceVersion == 2) {
        sourcePackage = _V2_PACKAGE;
        destinationPackage = _V1_PACKAGE;
    }

    Class<?> sourceClass = source.getClass();

    String sourceClassName = sourceClass.getSimpleName();

    Object destination = null;

    if (sourceClass.isArray()) {
        destination = source;

        Class<?> componentType = sourceClass.getComponentType();

        if (componentType.getName().contains(sourcePackage)) {
            Object[] sourceArray = (Object[]) source;

            Class<?> destinationComponentType = Class
                    .forName(destinationPackage + componentType.getSimpleName());

            Object[] destinationArray = (Object[]) Array.newInstance(destinationComponentType,
                    sourceArray.length);

            for (int i = 0; i < sourceArray.length; i++) {
                Object sourceArrayValue = sourceArray[i];

                destinationArray[i] = convert(sourceArrayValue, sourceVersion);
            }

            destination = destinationArray;
        }
    } else if (sourceClass == CookieProtocol.class) {
        CookieProtocol cookieProtocol = (CookieProtocol) source;

        destination = oasis.names.tc.wsrp.v2.types.CookieProtocol.fromValue(cookieProtocol.getValue());
    } else if (sourceClass == oasis.names.tc.wsrp.v2.types.CookieProtocol.class) {

        oasis.names.tc.wsrp.v2.types.CookieProtocol cookieProtocol = (oasis.names.tc.wsrp.v2.types.CookieProtocol) source;

        destination = CookieProtocol.fromValue(cookieProtocol.getValue());
    } else if (sourceClass == StateChange.class) {
        StateChange stateChange = (StateChange) source;

        destination = oasis.names.tc.wsrp.v2.types.StateChange.fromValue(stateChange.getValue());
    } else if (sourceClass == oasis.names.tc.wsrp.v2.types.StateChange.class) {

        oasis.names.tc.wsrp.v2.types.StateChange stateChange = (oasis.names.tc.wsrp.v2.types.StateChange) source;

        destination = StateChange.fromValue(stateChange.getValue());
    } else {
        Class<?> destinationClass = Class.forName(destinationPackage + sourceClassName);

        destination = destinationClass.newInstance();

        Map<String, Object> sourceChildren = PropertyUtils.describe(source);

        for (Map.Entry<String, Object> sourceChildEntry : sourceChildren.entrySet()) {

            String sourceChildName = sourceChildEntry.getKey();

            if (sourceChildName.equals("class")) {
                continue;
            }

            Object sourceChild = sourceChildEntry.getValue();

            if (sourceChild == null) {
                continue;
            }

            _convert(sourceVersion, sourcePackage, sourceClass, sourceChild, sourceChildName, destination);
        }
    }

    return destination;
}

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

public static void setEntity(final StructEntityReflect enref, final HashMap<String, AbstractEntity> entities,
        final ResultSet rs) throws Exception {
    Class<?> type = Class.forName(enref.Class);
    Object obj = type.newInstance();
    if (!(obj instanceof AbstractEntity))
        throw new Exception("Unsupported Entity type [" + type.getCanonicalName() + "]");
    AbstractEntity entity = (AbstractEntity) obj;
    AbstractJoinGraph gr = AbstractJoinGraph.lookup(type);

    for (StructAttributeReflect attr : enref.Attributes) {
        Stack<KeyValuePair<Class<?>>> path = new Stack<KeyValuePair<Class<?>>>();
        Class<?> at = attr.Field.getType();
        KeyValuePair<Class<?>> ak = new KeyValuePair<Class<?>>();
        ak.setValue(entity.getClass());//  w  w w .j av a 2  s  . co  m
        ak.setKey(attr.Column);
        path.push(ak);

        if (attr.Reference == null || attr.Reference.Type != EnumRefereceType.One2Many) {
            setColumnValue(rs, attr, entity, gr, path);
        } else if (attr.Reference != null) {
            // Object ao = createListInstance(entity, attr);
            Class<?> rt = Class.forName(attr.Reference.Class);
            Object ro = rt.newInstance();
            if (!(ro instanceof AbstractEntity))
                throw new Exception(
                        "Reference [" + attr.Column + "] is of invalid type. [" + at.getCanonicalName()
                                + "] does not extend from [" + AbstractEntity.class.getCanonicalName() + "]");
            AbstractEntity ae = (AbstractEntity) getColumnValue(rs, attr, entity, gr, path);
            addListValue(ae, entity, attr);
        }

    }
    String key = entity.getEntityKey();
    if (!entities.containsKey(key)) {
        entities.put(entity.getEntityKey(), entity);
    } else {
        AbstractEntity target = entities.get(key);
        for (StructAttributeReflect attr : enref.Attributes) {
            if (attr.Reference.Type == EnumRefereceType.One2Many) {
                copyToList(entity, target, attr);
            }
        }
    }
}

From source file:org.usergrid.mongo.commands.MongoCommand.java

@SuppressWarnings("unchecked")
public static MongoCommand getCommand(String commandName) {
    MongoCommand command = commands.get(commandName);
    if (command != null) {
        return command;
    }/*from  w w w . j a va 2 s  .  c  om*/

    String clazz = "org.usergrid.mongo.commands." + StringUtils.capitalize(commandName);

    Class<MongoCommand> cls = null;

    try {
        cls = (Class<MongoCommand>) Class.forName(clazz);
    } catch (ClassNotFoundException e) {
        logger.error("Couldn't find command class", e);
    }

    try {
        if (cls != null) {
            command = cls.newInstance();
        }
    } catch (Exception e) {
        logger.error("Couldn't find instantiate class", e);
    }

    if (command != null) {
        MongoCommand oldCommand = commands.putIfAbsent(commandName, command);
        if (oldCommand != null) {
            command = oldCommand;
        }
    } else {
        logger.warn("Mongo command handler not found for " + commandName);
    }

    return command;
}

From source file:com.ricemap.spateDB.core.SpatialSite.java

/**
 * Creates a stock shape according to the given configuration
 * @param job//from w  w  w  .  j  a  va2  s  . c o m
 * @return
 */
public static Shape createStockShape(Configuration job) {
    Shape stockShape = null;
    try {
        Class<? extends Shape> shapeClass = getShapeClass(job);
        stockShape = shapeClass.newInstance();
    } catch (InstantiationException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }
    return stockShape;
}

From source file:grails.util.Holders.java

@SuppressWarnings("unchecked")
private static void createServletContextsHolder() {
    try {// ww  w  . j a v a  2 s  . c o m
        Class<?> clazz = Holders.class.getClassLoader()
                .loadClass("org.codehaus.groovy.grails.web.context.WebRequestServletHolder");
        servletContexts = (Holder<ServletContext>) clazz.newInstance();
    } catch (ClassNotFoundException e) {
        // shouldn't happen
        LOG.error("Error initializing servlet context holder", e);
    } catch (InstantiationException e) {
        // shouldn't happen
        LOG.error("Error initializing servlet context holder", e);
    } catch (IllegalAccessException e) {
        // shouldn't happen
        LOG.error("Error initializing servlet context holder", e);
    }
}

From source file:com.sinosoft.one.mvc.util.MvcBeanUtils.java

@SuppressWarnings("unchecked")
public static Object instantiateClass(Class clazz) throws BeanInstantiationException {
    // spring's : Object mappedObject = BeanUtils.instantiateClass(this.mappedClass);
    // jade's : private Object instantiateClass(this.mappedClass);
    // why: ??mappedClass.newInstranceBeanUtils.instantiateClass(mappedClass)1?
    try {//from w  w w  .  j a va 2  s . c  o m
        return clazz.newInstance();
    } catch (Exception ex) {
        throw new BeanInstantiationException(clazz, ex.getMessage(), ex);
    }
}

From source file:com.jilk.ros.rosbridge.implementation.JSON.java

private static Message convertJSONArrayToMessage(JSONArray ja, Class c, Registry<Class> r) {
    try {/*  w w w  .ja  v a2 s  . c o  m*/
        Message result = (Message) c.newInstance();
        int arrayIndex = 0;
        for (Field f : c.getFields()) {
            Class fc = getFieldClass(result, null, f, r);
            Object lookup = ja.get(arrayIndex++); // yes we are assuming that the fields are delivered in order
            if (lookup != null) {
                Object value = convertElementToField(lookup, fc, f, r);
                f.set(result, value);
            }
        }

        return result;
    } catch (Exception ex) {
        ex.printStackTrace();
        return null;
    }
}

From source file:com.yunmel.syncretic.utils.commons.CollectionsUtils.java

public static <T extends BaseEntity> List<T> maplist2EntityMapList(List<Map<String, Object>> mapList,
        Class<T> beanClass) {
    List<T> newList = Lists.newArrayList();
    for (Map<String, Object> map : mapList) {
        try {//from w  ww  . j  a v a2 s.  co  m
            T t = beanClass.newInstance();
            t.setAll(map);
            newList.add(t);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return newList;
}

From source file:com.frameworkset.platform.sanylog.common.BeanConvertUtil.java

/**
 * Map??Bean?./*w  ww. j  a  v  a  2s  .  c o  m*/
 * 
 * @param clazz
 * @param dataMap ?Map
 * @param fieldMap Map??fieldName
 * @return
 * @throws InstantiationException
 * @throws IllegalAccessException
 * @throws IllegalArgumentException
 * @throws InvocationTargetException
 * @throws NoSuchMethodException 
 */
public static <T> T convert(Class<T> clazz, Map<String, Object> dataMap, Map<String, String> fieldMap)
        throws InstantiationException, IllegalAccessException, IllegalArgumentException,
        InvocationTargetException, NoSuchMethodException {
    T obj = clazz.newInstance();
    ClassInfo classInfo = ClassUtil.getClassInfo(clazz);
    for (String mapKey : fieldMap.keySet()) {
        Object value = dataMap.get(mapKey);
        String fieldName = fieldMap.get(mapKey);
        if (value != null) {
            //classInfo.getDeclaredField(fieldName).set(obj, value);
            PropertieDescription pd = classInfo.getPropertyDescriptor(fieldName);
            //??
            Class<?> pclazz = pd.getPropertyType();

            if (Timestamp.class.isAssignableFrom(pclazz)) {
                if (value instanceof Date) {
                    pd.setValue(obj, new Timestamp(((Date) value).getTime()));
                }
            } else if (Date.class.isAssignableFrom(pclazz)) {
                //String
                if (value instanceof Date) {
                    pd.setValue(obj, value);
                }
            } else {
                Object targetValue = pclazz.getConstructor(String.class).newInstance(value.toString());
                if (String.class.isAssignableFrom(pclazz) && value instanceof Number) {
                    targetValue = new DecimalFormat("0").format(value);
                }
                pd.setValue(obj, targetValue);
            }
            //PropertyUtils.setProperty(obj, fieldName, value);
        }
    }
    return obj;
}

From source file:com.tractionsoftware.reshoot.Reshoot.java

private static Setup getSetup(Configuration configuration, Screenshot screenshot) {
    if (configuration.setups != null && screenshot.setup != null) {
        Class cls;
        try {//from w  ww.ja  v  a2  s .c  o  m
            Map<String, String> setup = configuration.setups.get(screenshot.setup);
            cls = Class.forName(setup.get("class"));
            Setup s = (Setup) cls.newInstance();
            s.init(setup);
            return s;
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
            e.printStackTrace();
        }
    }
    return null;
}