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:dk.itst.oiosaml.sp.service.util.Utils.java

public static Object newInstance(Configuration cfg, String property) {
    String name = cfg.getString(property);
    if (name == null) {
        throw new IllegalArgumentException("Property " + property + " has not been set");
    }/* w  w w . ja va  2 s .c o  m*/

    try {
        Class<?> c = Class.forName(name);

        return c.newInstance();
    } catch (Exception e) {
        throw new RuntimeException("Unable to create instance of " + name, e);
    }
}

From source file:Main.java

public static <T extends Fragment> T addFragmentToActivity(@NonNull FragmentManager fragmentManager,
        @NonNull Class<T> clz, @NonNull Integer frameId) {
    checkNotNull(fragmentManager);// w w w .j a v  a  2s .  co  m
    checkNotNull(clz);
    checkNotNull(frameId);
    T fragment = (T) fragmentManager.findFragmentById(frameId);
    if (fragment == null) {
        try {
            fragment = clz.newInstance();
            FragmentTransaction transaction = fragmentManager.beginTransaction();
            transaction.add(frameId, fragment);
            transaction.commit();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }
    return fragment;
}

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

static void configureDeserializationProblemHandlers(final ObjectMapper objectMapper,
        final String deserializationProblemHandlers, final ClassLoader classLoader) throws Exception {
    final StringTokenizer st = new StringTokenizer(deserializationProblemHandlers, ", ");
    while (st.hasMoreTokens()) {
        final Class<?> c = classLoader.loadClass(st.nextToken());
        objectMapper.addHandler((DeserializationProblemHandler) c.newInstance());
    }/*from  w w  w  .  ja va2  s . co m*/
}

From source file:com.momock.util.DataHelper.java

@SuppressWarnings("unchecked")
public static <T, I extends IDataMap<String, Object>> DataList<T> getBeanList(IDataList<I> nodes,
        Class<T> beanClass) {
    DataList<T> dl = new DataList<T>();
    for (int i = 0; i < nodes.getItemCount(); i++) {
        try {/*from  w w  w  .j  a v a 2  s.  c o  m*/
            T obj = beanClass.newInstance();
            if (obj instanceof IDataMutableMap) {
                IDataMutableMap<String, Object> target = (IDataMutableMap<String, Object>) obj;
                target.copyPropertiesFrom(nodes.getItem(i));
            } else {
                BeanHelper.copyPropertiesFromDataMap(obj, nodes.getItem(i));
            }
            dl.addItem(obj);
        } catch (Exception e) {
            Logger.error(e);
        }
    }
    return dl;
}

From source file:com.ms.commons.test.common.ReflectUtil.java

public static <T> T newInstance(Class<T> clazz) {
    try {//from w w w .  j a v  a  2 s  .c om
        return clazz.newInstance();
    } catch (Exception e) {
        throw ExceptionUtil.wrapToRuntimeException(e);
    }
}

From source file:de.tudarmstadt.ukp.dkpro.tc.core.util.SaveModelUtils.java

public static void writeModelParameters(TaskContext aContext, File aOutputFolder, List<String> aFeatureSet,
        List<Object> aFeatureParameters) throws Exception {
    // write meta collector data
    // automatically determine the required metaCollector classes from the
    // provided feature
    // extractors
    Set<Class<? extends MetaCollector>> metaCollectorClasses;
    try {//  w  ww .  j a v a2s.c  om
        metaCollectorClasses = TaskUtils.getMetaCollectorsFromFeatureExtractors(aFeatureSet);
    } catch (ClassNotFoundException e) {
        throw new ResourceInitializationException(e);
    } catch (InstantiationException e) {
        throw new ResourceInitializationException(e);
    } catch (IllegalAccessException e) {
        throw new ResourceInitializationException(e);
    }

    // collect parameter/key pairs that need to be set
    Map<String, String> metaParameterKeyPairs = new HashMap<String, String>();
    for (Class<? extends MetaCollector> metaCollectorClass : metaCollectorClasses) {
        try {
            metaParameterKeyPairs.putAll(metaCollectorClass.newInstance().getParameterKeyPairs());
        } catch (InstantiationException e) {
            throw new ResourceInitializationException(e);
        } catch (IllegalAccessException e) {
            throw new ResourceInitializationException(e);
        }
    }

    Properties parameterProperties = new Properties();
    for (Entry<String, String> entry : metaParameterKeyPairs.entrySet()) {
        File file = new File(aContext.getStorageLocation(META_KEY, AccessMode.READWRITE), entry.getValue());

        String name = file.getName();
        String subFolder = aOutputFolder.getAbsoluteFile() + "/" + name;
        File targetFolder = new File(subFolder);
        copyToTargetLocation(file, targetFolder);
        parameterProperties.put(entry.getKey(), name);

        // should never be reached
    }

    for (int i = 0; i < aFeatureParameters.size(); i = i + 2) {

        String key = (String) aFeatureParameters.get(i).toString();
        String value = aFeatureParameters.get(i + 1).toString();

        if (valueExistAsFileOrFolderInTheFileSystem(value)) {
            String name = new File(value).getName();
            String destination = aOutputFolder + "/" + name;
            copyToTargetLocation(new File(value), new File(destination));
            parameterProperties.put(key, name);
            continue;
        }
        parameterProperties.put(key, value);
    }

    FileWriter writer = new FileWriter(new File(aOutputFolder, MODEL_PARAMETERS));
    parameterProperties.store(writer, "");
    writer.close();
}

From source file:org.jruby.rack.mock.MockAsyncContext.java

private static <T> T instantiate(Class<T> clazz) throws IllegalArgumentException {
    if (clazz.isInterface()) {
        throw new IllegalArgumentException(clazz + " is an interface");
    }//from   w w  w . jav a  2 s.  c  om
    try {
        return clazz.newInstance();
    } catch (InstantiationException ex) {
        throw new IllegalArgumentException(clazz + " is it an abstract class?", ex);
    } catch (IllegalAccessException ex) {
        throw new IllegalArgumentException(clazz + " constructor accessible?", ex);
    }
}

From source file:com.microsoft.tfs.core.httpclient.cookie.CookiePolicy.java

/**
 * Gets the {@link CookieSpec cookie specification} with the given ID.
 *
 * @param id/*  ww  w  . ja  v  a  2  s.  co  m*/
 *        the {@link CookieSpec cookie specification} ID
 *
 * @return {@link CookieSpec cookie specification}
 *
 * @throws IllegalStateException
 *         if a policy with the ID cannot be found
 *
 * @since 3.0
 */
public static CookieSpec getCookieSpec(final String id) throws IllegalStateException {

    if (id == null) {
        throw new IllegalArgumentException("Id may not be null");
    }
    final Class<? extends CookieSpec> clazz = SPECS.get(id.toLowerCase());

    if (clazz != null) {
        try {
            return clazz.newInstance();
        } catch (final Exception e) {
            LOG.error("Error initializing cookie spec: " + id, e);
            throw new IllegalStateException(
                    id + " cookie spec implemented by " + clazz.getName() + " could not be initialized");
        }
    } else {
        throw new IllegalStateException("Unsupported cookie spec " + id);
    }
}

From source file:net.aepik.alasca.plugin.schemaconverter.SCTool.java

/**
 * Create a SchemaSyntax object from a valid syntax name.
 * @param String syntaxName A valid syntax name.
 * @return SchemaSyntax/*  w  ww  .jav a 2  s .  com*/
 */
private static SchemaSyntax createSchemaSyntax(String syntaxName) {
    SchemaSyntax syntax = null;
    try {
        String syntaxClassName = Schema.getSyntaxPackageName() + "." + syntaxName;
        @SuppressWarnings("unchecked")
        Class<SchemaSyntax> syntaxClass = (Class<SchemaSyntax>) Class.forName(syntaxClassName);
        syntax = syntaxClass.newInstance();
    } catch (Exception e) {
        e.printStackTrace();
    }
    ;
    return syntax;
}

From source file:it.nicola_amatucci.util.Json.java

public static <T> T object_from_json(JSONObject json, Class<T> objClass) throws Exception {
    T t = null;/*  w w w.j av a2s. c  o  m*/
    Object o = null;

    try {
        //create new object instance
        t = objClass.newInstance();

        //object fields
        Field[] fields = objClass.getFields();

        for (Field field : fields) {
            //field name
            o = json.get(field.getName());

            if (o.equals(null))
                continue;

            //field value
            try {
                String typeName = field.getType().getSimpleName();

                if (typeName.equals("String")) {
                    o = json.getString(field.getName()); //String
                } else if (typeName.equals("boolean")) {
                    o = Integer.valueOf(json.getInt(field.getName())); //boolean
                } else if (typeName.equals("int")) {
                    o = Integer.valueOf(json.getInt(field.getName())); //int
                } else if (typeName.equals("long")) {
                    o = Long.valueOf(json.getLong(field.getName())); //long                  
                } else if (typeName.equals("double")) {
                    o = Double.valueOf(json.getDouble(field.getName())); //double
                } else if (typeName.equals("Date")) {
                    o = new SimpleDateFormat(Json.DATA_FORMAT).parse(o.toString()); //data
                } else if (field.getType().isArray()) {
                    JSONArray arrayJSON = new JSONArray(o.toString());
                    T[] arrayOfT = (T[]) null;

                    try {
                        //create object array
                        Class c = Class.forName(field.getType().getName()).getComponentType();
                        arrayOfT = (T[]) Array.newInstance(c, arrayJSON.length());

                        //parse objects                  
                        for (int i = 0; i < json.length(); i++)
                            arrayOfT[i] = (T) object_from_json(arrayJSON.getJSONObject(i), c);
                    } catch (Exception e) {
                        throw e;
                    }

                    o = arrayOfT;
                } else {
                    o = object_from_json(new JSONObject(o.toString()), field.getType()); //object
                }

            } catch (Exception e) {
                throw e;
            }

            t.getClass().getField(field.getName()).set(t, o);
        }

    } catch (Exception e) {
        throw e;
    }

    return t;
}