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.aol.advertising.qiao.util.ContextUtils.java

/**
 * Locate a Spring bean of the given class. If not found, instantiate a new
 * instance of the class.// w  w w . j  a  va2 s  .  c om
 *
 * @param clzname
 *            class name
 * @return the object of the class
 * @throws ClassNotFoundException
 */
public static Object getOrCreateBean(String clzname) throws ClassNotFoundException {
    Object o = null;
    Class<?> clz = Class.forName(clzname);
    try {
        o = ContextUtils.getBean(clz);
    } catch (NoSuchBeanDefinitionException e) {
        try {
            o = clz.newInstance();
        } catch (Exception e1) {
            logger.error("Failed to instantiate class " + clzname);
        }
    }

    return o;
}

From source file:com.xidu.framework.common.util.Utils.java

public static List<?> convertDomainListToDtoList(List<?> origDomainList, Class<?> dtoClass) {
    if (null == origDomainList) {
        return null;
    }// w  ww . jav a2 s  . c o m
    List<Object> convertedList = new ArrayList<Object>();
    for (Object orig : origDomainList) {
        Object dest;
        try {
            dest = dtoClass.newInstance();
            ConvertUtils.register(new DateConverter(null), Date.class);
            BeanUtils.copyProperties(dest, orig);
            convertedList.add(dest);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    return convertedList;
}

From source file:org.jberet.support.io.JsonItemReader.java

protected static JsonParser configureJsonParser(final JsonItemReaderWriterBase batchReaderArtifact,
        final Class<?> inputDecorator, final String deserializationProblemHandlers,
        final Map<String, String> jsonParserFeatures) throws Exception {
    final JsonParser jsonParser;
    if (inputDecorator != null) {
        batchReaderArtifact.jsonFactory.setInputDecorator((InputDecorator) inputDecorator.newInstance());
    }/*w  w  w. j  a  v a  2s  . c o m*/

    jsonParser = batchReaderArtifact.jsonFactory
            .createParser(getInputStream(batchReaderArtifact.resource, false));

    if (deserializationProblemHandlers != null) {
        MappingJsonFactoryObjectFactory.configureDeserializationProblemHandlers(
                batchReaderArtifact.objectMapper, deserializationProblemHandlers,
                batchReaderArtifact.getClass().getClassLoader());
    }
    SupportLogger.LOGGER.openingResource(batchReaderArtifact.resource, batchReaderArtifact.getClass());

    if (jsonParserFeatures != null) {
        for (final Map.Entry<String, String> e : jsonParserFeatures.entrySet()) {
            final String key = e.getKey();
            final String value = e.getValue();
            final JsonParser.Feature feature;
            try {
                feature = JsonParser.Feature.valueOf(key);
            } catch (final Exception e1) {
                throw SupportMessages.MESSAGES.unrecognizedReaderWriterProperty(key, value);
            }
            if ("true".equals(value)) {
                if (!feature.enabledByDefault()) {
                    jsonParser.configure(feature, true);
                }
            } else if ("false".equals(value)) {
                if (feature.enabledByDefault()) {
                    jsonParser.configure(feature, false);
                }
            } else {
                throw SupportMessages.MESSAGES.invalidReaderWriterProperty(null, value, key);
            }
        }
    }

    return jsonParser;
}

From source file:org.exoplatform.social.client.api.util.SocialJSONDecodingSupport.java

/**
 * Parse JSON text into java Model object from the input source.
 * and then it's base on the class type.
 * /*  w  ww . jav  a2 s .com*/
 * @param <T> Generic type must extend from Model.
 * @param clazz Class type.
 * @param jsonContent Json content which you need to create the Model
 * @throws ParseException Throw this exception if any
 * 
 */
public static <T extends Model> T parser(final Class<T> clazz, String jsonContent) throws ParseException {
    JSONParser parser = new JSONParser();
    ContainerFactory containerFactory = new ContainerFactory() {
        public List<T> creatArrayContainer() {
            return new LinkedList<T>();
        }

        public T createObjectContainer() {
            try {
                return clazz.newInstance();
            } catch (InstantiationException e) {
                return null;
            } catch (IllegalAccessException e) {
                return null;
            }
        }
    };
    return (T) parser.parse(jsonContent, containerFactory);
}

From source file:com.vk.sdk.api.model.ParseUtils.java

/**
 * Parses array from given JSONArray.//  w w  w  .  jav  a2  s.c o  m
 * Supports parsing of primitive types and {@link com.vk.sdk.api.model.VKApiModel} instances.
 * @param array JSONArray to parse
 * @param arrayClass type of array field in class.
 * @return object to set to array field in class
 * @throws JSONException if given array have incompatible type with given field.
 */
private static Object parseArrayViaReflection(JSONArray array, Class arrayClass) throws JSONException {
    Object result = Array.newInstance(arrayClass.getComponentType(), array.length());
    Class<?> subType = arrayClass.getComponentType();
    for (int i = 0; i < array.length(); i++) {
        try {
            Object item = array.opt(i);
            if (VKApiModel.class.isAssignableFrom(subType) && item instanceof JSONObject) {
                VKApiModel model = (VKApiModel) subType.newInstance();
                item = model.parse((JSONObject) item);
            }
            Array.set(result, i, item);
        } catch (InstantiationException e) {
            throw new JSONException(e.getMessage());
        } catch (IllegalAccessException e) {
            throw new JSONException(e.getMessage());
        } catch (IllegalArgumentException e) {
            throw new JSONException(e.getMessage());
        }
    }
    return result;
}

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

@SuppressWarnings("unchecked")
private static <T> T cleanAndConvert(JSONObject jsonObject, Class<T> clazz) {
    try {/*w ww .  j  a  v  a2 s .c om*/
        Iterator<String> keys = jsonObject.keys();
        T instance = clazz.newInstance();
        while (keys.hasNext()) {
            String key = keys.next();
            if (!PropertyUtils.isWriteable(instance, key)) {
                keys.remove();
            }
        }
        return (T) JSONObject.toBean(jsonObject, clazz);
    } catch (Exception e) {
        throw new IllegalArgumentException("Could not convert from json to bean of type " + clazz.getName(), e);
    }
}

From source file:org.openmrs.module.webservices.rest.web.DelegatingCrudResourceTest.java

/**
 * Convenience method that checks if the specified property is included among the allowed
 * missing properties of the given resource class via reflection
 * //from www  .  ja  v  a  2  s .c o  m
 * @param clazz
 * @param fieldName
 * @return
 * @throws IllegalArgumentException
 * @throws IllegalAccessException
 * @throws InstantiationException
 */
@SuppressWarnings("rawtypes")
private static boolean isallowedMissingProperty(Class resourceClass, String propName)
        throws IllegalArgumentException, IllegalAccessException, InstantiationException {
    List<Field> fields = Reflect.getAllFields(resourceClass);
    if (CollectionUtils.isNotEmpty(fields)) {
        for (Field field : fields) {
            if (field.getName().equals("allowedMissingProperties"))
                return ((Set) field.get(resourceClass.newInstance())).contains(propName);
        }
    }
    return false;
}

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

/**
 * Gets object from json./*from   ww  w  .j a v a2 s  .c  om*/
 *
 * @param classEntity the class entity
 * @param bsonObject  the bson object
 * @return the object from json
 * @throws IllegalAccessException    the illegal access exception
 * @throws InstantiationException    the instantiation exception
 * @throws InvocationTargetException the invocation target exception
 */
public static <T> T getObjectFromJson(Class<T> classEntity, JSONObject bsonObject)
        throws IllegalAccessException, InstantiationException, InvocationTargetException {
    T t = classEntity.newInstance();

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

    Object insert = null;

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

            Class<?> classField = field.getType();

            currentBson = bsonObject.get(AnnotationUtils.deepFieldName(field));
            if (currentBson != null) {

                if (Iterable.class.isAssignableFrom(classField)) {
                    Type type = field.getGenericType();

                    insert = subDocumentListCase(type,
                            (List) bsonObject.get(AnnotationUtils.deepFieldName(field)));

                } else if (IDeepType.class.isAssignableFrom(classField)) {
                    insert = getObjectFromJson(classField,
                            (JSONObject) bsonObject.get(AnnotationUtils.deepFieldName(field)));
                } else {
                    insert = currentBson;
                }
                method.invoke(t, insert);
            }
        } catch (IllegalAccessException | InstantiationException | InvocationTargetException
                | IllegalArgumentException e) {
            LOG.error("impossible to create a java object from Bson field:" + field.getName() + " and type:"
                    + field.getType() + " and value:" + t + "; bsonReceived:" + currentBson
                    + ", bsonClassReceived:" + currentBson.getClass());

            method.invoke(t, Utils.castNumberType(insert, t.getClass()));
        }

    }

    return t;
}

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

public static <T> T getObjectWithMapFromJson(Class<T> classEntity, JSONObject bsonObject)
        throws IllegalAccessException, InstantiationException, InvocationTargetException {
    T t = classEntity.newInstance();

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

    Object insert = null;/*  ww  w  .  j a v  a 2s .co m*/

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

            Class<?> classField = field.getType();

            currentBson = bsonObject.get(AnnotationUtils.deepFieldName(field));
            if (currentBson != null) {

                if (Collection.class.isAssignableFrom(classField)) {
                    Type type = field.getGenericType();
                    List list = new ArrayList();
                    for (Object o : (List) bsonObject.get(AnnotationUtils.deepFieldName(field))) {
                        list.add((String) o);
                    }
                    insert = list;

                } else if (IDeepType.class.isAssignableFrom(classField)) {
                    insert = getObjectFromJson(classField,
                            (JSONObject) bsonObject.get(AnnotationUtils.deepFieldName(field)));
                } else {
                    insert = currentBson;
                }
                if (insert != null) {
                    method.invoke(t, insert);
                }

            }
        } catch (IllegalAccessException | InstantiationException | InvocationTargetException
                | IllegalArgumentException e) {
            LOG.error("impossible to create a java object from Bson field:" + field.getName() + " and type:"
                    + field.getType() + " and value:" + t + "; bsonReceived:" + currentBson
                    + ", bsonClassReceived:" + currentBson.getClass());
            method.invoke(t, Utils.castNumberType(insert, t.getClass()));
        }

    }

    return t;
}

From source file:de.tbuchloh.kiskis.gui.dialogs.SecuredElementCreationDlg.java

/**
 * Factory ...//from   w ww  .  ja  v a  2s .co m
 * 
 * @param owner
 *            dialog owner.
 * @param defaultExpiryTime
 *            time after the password epires in days
 * @return the generated element or null if nothing was selected
 */
public static SecuredElement newInstance(final JFrame owner, final TPMDocument doc,
        final int defaultExpiryTime) {
    final SecuredElementCreationDlg dlg = new SecuredElementCreationDlg(owner, doc);
    dlg.setVisible(true);
    if (dlg._pressedButton == APPROVED_BUTTON) {

        final Class clazz = dlg.getSelectedClass();

        LOG.info("Creating new element - class=" + clazz + ", expiryTime=" + defaultExpiryTime);

        if (clazz != null) {
            try {
                final SecuredElement el = (SecuredElement) clazz.newInstance();
                el.setPwd(new Password(new char[0], defaultExpiryTime));
                if (el instanceof GenericAccount) {
                    final GenericAccount a = (GenericAccount) el;
                    a.setType(dlg.getSelectedTemplate());
                }
                return el;
            } catch (final InstantiationException e) {
                throw new Error("Should not happen"); //$NON-NLS-1$
            } catch (final IllegalAccessException e) {
                throw new Error("Should not happen"); //$NON-NLS-1$
            }
        }
    }
    return null;
}