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:de.innovationgate.wga.common.beans.csconfig.v1.CSConfig.java

public static CSConfig instantiateCSConfig(Class<? extends CSConfig> clazz) {

    try {/*from www . j  a v a2 s. com*/
        CSConfig csconfig = (CSConfig) clazz.newInstance();
        return csconfig;
    } catch (InstantiationException e) {
        throw new RuntimeException("Cannot instantiate " + clazz.getName(), e);
    } catch (IllegalAccessException e) {
        throw new RuntimeException("Cannot instantiate " + clazz.getName(), e);
    }

}

From source file:com.reactivetechnologies.platform.rest.WebbitRestServerBean.java

/**
 * /*ww w .  j a v  a2 s  .  c om*/
 * @param restletClass
 * @return
 * @throws InstantiationException
 * @throws IllegalAccessException
 */
static JAXRSInstanceMetadata scanJaxRsClass(Class<?> restletClass)
        throws InstantiationException, IllegalAccessException {
    final JAXRSInstanceMetadata proxy = new JAXRSInstanceMetadata(restletClass.newInstance());
    if (restletClass.isAnnotationPresent(Path.class)) {
        String rootUri = restletClass.getAnnotation(Path.class).value();
        if (rootUri == null)
            rootUri = "";
        proxy.setRootUri(rootUri);
    }
    ReflectionUtils.doWithMethods(restletClass, new MethodCallback() {

        @Override
        public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
            String subUri = "";
            if (method.isAnnotationPresent(Path.class)) {
                subUri = method.getAnnotation(Path.class).value();
            }
            if (method.isAnnotationPresent(GET.class)) {
                MethodDetail m = createMethodDetail(method);
                proxy.addGetMethod(proxy.getRootUri() + subUri, m);
            }
            if (method.isAnnotationPresent(POST.class)) {
                MethodDetail m = createMethodDetail(method);
                proxy.addPostMethod(proxy.getRootUri() + subUri, m);
            }
            if (method.isAnnotationPresent(DELETE.class)) {
                MethodDetail m = createMethodDetail(method);
                proxy.addDelMethod(proxy.getRootUri() + subUri, m);
            }

        }
    }, new MethodFilter() {

        @Override
        public boolean matches(Method method) {
            return (method.isAnnotationPresent(GET.class) || method.isAnnotationPresent(POST.class)
                    || method.isAnnotationPresent(DELETE.class));
        }
    });

    return proxy;
}

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

/**
 * Create a new instance of an AbstractEntity type. This method should be
 * used when creating new AbstarctEntity types.
 * //  w  w w.j a  va  2  s . co m
 * @param type
 *            - Class (type) to create instance of.
 * 
 * @return
 * @throws Exception
 */
@SuppressWarnings("unchecked")
public static <T extends AbstractEntity> T newInstance(final Class<?> type) throws Exception {
    Object obj = type.newInstance();
    if (!(obj instanceof AbstractEntity))
        throw new Exception("Invalid Class : [" + type.getCanonicalName() + "] does not extend ["
                + AbstractEntity.class.getCanonicalName() + "]");

    ((AbstractEntity) obj).setState(EnumEntityState.New);

    return (T) obj;
}

From source file:edu.cornell.mannlib.vitro.webapp.utils.pageDataGetter.PageDataGetterUtils.java

/***
 * For the page, get the actual Data Getters to be employed.
 * @throws ClassNotFoundException //  w  w  w. ja  va2s .c om
 * @throws IllegalAccessException 
 * @throws InstantiationException 
 */
public static List<PageDataGetter> getPageDataGetterObjects(VitroRequest vreq, String pageUri)
        throws InstantiationException, IllegalAccessException, ClassNotFoundException {
    List<PageDataGetter> dataGetterObjects = new ArrayList<PageDataGetter>();

    List<String> dataGetterClassNames = vreq.getWebappDaoFactory().getPageDao().getDataGetterClass(pageUri);
    if (dataGetterClassNames == null)
        return Collections.emptyList();

    for (String dgClassName : dataGetterClassNames) {
        String className = getClassNameFromUri(dgClassName);
        Class clz = Class.forName(className);

        if (PageDataGetter.class.isAssignableFrom(clz)) {
            PageDataGetter pg = (PageDataGetter) clz.newInstance();
            dataGetterObjects.add(pg);
        } // else skip if class does not implement PageDataGetter
    }

    return dataGetterObjects;
}

From source file:net.jradius.server.config.Configuration.java

public static Object getBean(String name)
        throws IllegalAccessException, ClassNotFoundException, InstantiationException {
    Object o = null;//  w  ww.  j  a  va  2s.c  om
    if (name.startsWith("bean:")) {
        String s[] = name.split(":");
        o = beanFactory.getBean(s[1]);
    } else {
        Class clazz = Class.forName(name);
        o = clazz.newInstance();
        if (o instanceof InitializingBean) {
            try {
                ((InitializingBean) o).afterPropertiesSet();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    return o;
}

From source file:be.fedict.commons.eid.consumer.tlv.TlvParser.java

private static <T> T parseThrowing(final byte[] file, final Class<T> tlvClass) throws InstantiationException,
        IllegalAccessException, DataConvertorException, UnsupportedEncodingException {
    final Field[] fields = tlvClass.getDeclaredFields();
    final Map<Integer, Field> tlvFields = new HashMap<Integer, Field>();
    final T tlvObject = tlvClass.newInstance();
    for (Field field : fields) {
        final TlvField tlvFieldAnnotation = field.getAnnotation(TlvField.class);
        if (null != tlvFieldAnnotation) {
            final int tagId = tlvFieldAnnotation.value();
            if (tlvFields.containsKey(new Integer(tagId))) {
                throw new IllegalArgumentException("TLV field duplicate: " + tagId);
            }/*from   w  ww  .j  a va 2s. c  o  m*/
            tlvFields.put(new Integer(tagId), field);
        }
        final OriginalData originalDataAnnotation = field.getAnnotation(OriginalData.class);
        if (null != originalDataAnnotation) {
            field.setAccessible(true);
            field.set(tlvObject, file);
        }
    }

    int idx = 0;
    while (idx < file.length - 1) {
        final byte tag = file[idx];
        idx++;
        byte lengthByte = file[idx];
        int length = lengthByte & 0x7f;
        while ((lengthByte & 0x80) == 0x80) {
            idx++;
            lengthByte = file[idx];
            length = (length << 7) + (lengthByte & 0x7f);
        }
        idx++;
        if (0 == tag) {
            idx += length;
            continue;
        }
        if (tlvFields.containsKey(new Integer(tag))) {
            final Field tlvField = tlvFields.get(new Integer(tag));
            final Class<?> tlvType = tlvField.getType();
            final ConvertData convertDataAnnotation = tlvField.getAnnotation(ConvertData.class);
            final byte[] tlvValue = copy(file, idx, length);
            Object fieldValue;
            if (null != convertDataAnnotation) {
                final Class<? extends DataConvertor<?>> dataConvertorClass = convertDataAnnotation.value();
                final DataConvertor<?> dataConvertor = dataConvertorClass.newInstance();
                fieldValue = dataConvertor.convert(tlvValue);
            } else if (String.class == tlvType) {
                fieldValue = new String(tlvValue, "UTF-8");
            } else if (Boolean.TYPE == tlvType) {
                fieldValue = true;
            } else if (tlvType.isArray() && Byte.TYPE == tlvType.getComponentType()) {
                fieldValue = tlvValue;
            } else {
                throw new IllegalArgumentException("unsupported field type: " + tlvType.getName());
            }
            if (null != tlvField.get(tlvObject) && false == tlvField.getType().isPrimitive()) {
                throw new RuntimeException("field was already set: " + tlvField.getName());
            }
            tlvField.setAccessible(true);
            tlvField.set(tlvObject, fieldValue);
        } else {
            LOG.debug("unknown tag: " + (tag & 0xff) + ", length: " + length);
        }
        idx += length;
    }
    return tlvObject;
}

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

private static Message convertJSONObjectToMessage(JSONObject jo, Class c, Registry<Class> r) {
    //System.out.println("JSON.convertJSONObjectToMessage: " + jo.toJSONString());
    try {//from w  w w .  j  a  va  2 s  . c om
        Message result = (Message) c.newInstance();
        for (Field f : c.getFields()) {
            Class fc = getFieldClass(result, jo, f, r);
            Object lookup = jo.get(f.getName());
            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:grails.plugin.searchable.internal.lucene.LuceneUtils.java

/**
 * Returns a list of terms by parsing the given query string - special query characters and words (OR/AND) are
 * not included in the returned list//from w  w w . ja v  a  2 s .  c o  m
 *
 * @param queryString the query string to parse
 * @param analyzerClass the Analyzer Class instance to instantiate, may be null in which case Lucene's
 * StandardAnalyzer is used
 * @return a list of text terms
 */
public static String[] termsForQueryString(String queryString, Class analyzerClass) throws ParseException {
    if (analyzerClass == null) {
        return termsForQueryString(queryString, (Analyzer) null);
    }
    try {
        return termsForQueryString(queryString, (Analyzer) analyzerClass.newInstance());
    } catch (Exception ex) {
        // Convert to unchecked
        LOG.error("Failed to create instance of Analyzer class [" + analyzerClass + "]: " + ex, ex);
        throw new IllegalStateException(
                "Failed to create instance of Analyzer class [" + analyzerClass + "]: " + ex);
    }
}

From source file:ezbake.thrift.ThriftUtils.java

/**
 * Deserialize a thrift object/*from  ww w.ja  v  a 2 s  .c  o  m*/
 *
 * @param type The type of object
 * @param bytes The bytes of the object
 * @param <T> The type of object
 * @return The object
 */
public static <T extends TBase<?, ?>> T deserialize(Class<T> type, byte[] bytes) throws TException {
    final TDeserializer deserializer = new TDeserializer();
    try {
        final T object = type.newInstance();
        deserializer.deserialize(object, bytes);
        return object;
    } catch (final Exception ex) {
        throw new TException(ex);
    }
}

From source file:org.frat.common.converter.ConverterService.java

/**
 * Description: this method will be removed.
 * /*  w w  w . j av a  2s  .  c  om*/
 * @param source
 * @param targetClass
 * @param converter
 * @param customConverterClass
 * @return
 */
@Deprecated
@SuppressWarnings("unchecked")
private static <T, F> F convert(T source, Class<F> targetClass, Converter converter,
        Class<? extends ObjectConverter> customConverterClass) {
    if (source == null || targetClass == null) {
        return null;
    }
    if (source.getClass().equals(targetClass)) {
        return (F) source;
    }

    try {
        F target = targetClass.newInstance();
        copy(source, target, converter, customConverterClass);
        return target;
    } catch (InstantiationException e) {
        return null;
    } catch (IllegalAccessException e) {
        return null;
    }
}