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:io.openmessaging.rocketmq.utils.BeanUtils.java

/**
 * <p>Populate the JavaBeans properties of the specified bean, based on
 * the specified name/value pairs.  This method uses Java reflection APIs
 * to identify corresponding "property setter" method names, and deals
 * with setter arguments of type <Code>String</Code>, <Code>boolean</Code>,
 * <Code>int</Code>, <Code>long</Code>, <Code>float</Code>, and
 * <Code>double</Code>.</p>
 *
 * <p>The particular setter method to be called for each property is
 * determined using the usual JavaBeans introspection mechanisms.  Thus,
 * you may identify custom setter methods using a BeanInfo class that is
 * associated with the class of the bean itself.  If no such BeanInfo
 * class is available, the standard method name conversion ("set" plus
 * the capitalized name of the property in question) is used.</p>
 *
 * <p><strong>NOTE</strong>:  It is contrary to the JavaBeans Specification
 * to have more than one setter method (with different argument
 * signatures) for the same property.</p>
 *
 * @param clazz JavaBean class whose properties are being populated
 * @param properties Map keyed by property name, with the corresponding (String or String[]) value(s) to be set
 * @param <T> Class type/*from w  ww  . j a va 2  s.  co m*/
 * @return Class instance
 */
public static <T> T populate(final Properties properties, final Class<T> clazz) {
    T obj = null;
    try {
        obj = clazz.newInstance();
        return populate(properties, obj);
    } catch (Throwable e) {
        log.warn("Error occurs !", e);
    }
    return obj;
}

From source file:io.cloudex.framework.utils.ObjectUtils.java

/**
 * Create an instance of the provided class
 * @param classOfT - the type of the object to return
 * @param className - the full className
 * @return an instantiated object casted to type T
 * @throws ClassInstantiationException if the creation of the instance fails
 *//*from   w ww.  ja  v a 2s  . c  o  m*/
@SuppressWarnings("unchecked")
public static <T> T createInstance(Class<T> classOfT, String className) throws ClassInstantiationException {

    T object = null;
    try {
        Class<?> clazz = Class.forName(className);
        object = (T) clazz.newInstance();

    } catch (Exception e) {
        log.error("Failed to instantiate object from className: " + className, e);
        throw new ClassInstantiationException("Invalid className: " + className, e);
    }
    return object;
}

From source file:Main.java

public static int getStatusBarHeight(Context context) {
    Class<?> c = null;
    Object obj = null;/*from w  ww.  j  a v  a  2 s  . c  om*/
    Field field = null;
    int x = 0;
    int sbar = 0;
    try {
        c = Class.forName("com.android.internal.R$dimen");
        obj = c.newInstance();
        field = c.getField("status_bar_height");
        x = Integer.parseInt(field.get(obj).toString());
        sbar = context.getResources().getDimensionPixelSize(x);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return sbar;
}

From source file:Main.java

/**
 * @param type the type//  w w  w  . j  av a2 s  .c om
 * @return the default value of the provided type
 */
public static Object emptyValue(Class<?> type) {
    Object defaultValue = null;

    if (DEFAULTS.containsKey(type)) {
        defaultValue = DEFAULTS.get(type);
    } else {
        try {
            defaultValue = type.newInstance();
        } catch (Exception e) {
            // Ignore
        }
    }

    return defaultValue;
}

From source file:Main.java

public static Bitmap createVideoThumbnail(String filePath) {
    // MediaMetadataRetriever is available on API Level 8
    // but is hidden until API Level 10
    Class<?> clazz = null;
    Object instance = null;/*from   w ww. ja  v  a  2  s .  c  om*/
    try {
        clazz = Class.forName("android.media.MediaMetadataRetriever");
        instance = clazz.newInstance();

        Method method = clazz.getMethod("setDataSource", String.class);
        method.invoke(instance, filePath);

        // The method name changes between API Level 9 and 10.
        if (Build.VERSION.SDK_INT <= 9) {
            return (Bitmap) clazz.getMethod("captureFrame").invoke(instance);
        } else {
            byte[] data = (byte[]) clazz.getMethod("getEmbeddedPicture").invoke(instance);
            if (data != null) {
                Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
                if (bitmap != null)
                    return bitmap;
            }
            return (Bitmap) clazz.getMethod("getFrameAtTime").invoke(instance);
        }
    } catch (IllegalArgumentException ex) {
        // Assume this is a corrupt video file
    } catch (RuntimeException ex) {
        // Assume this is a corrupt video file.
    } catch (InstantiationException e) {
        Log.e(TAG, "createVideoThumbnail", e);
    } catch (InvocationTargetException e) {
        Log.e(TAG, "createVideoThumbnail", e);
    } catch (ClassNotFoundException e) {
        Log.e(TAG, "createVideoThumbnail", e);
    } catch (NoSuchMethodException e) {
        Log.e(TAG, "createVideoThumbnail", e);
    } catch (IllegalAccessException e) {
        Log.e(TAG, "createVideoThumbnail", e);
    } finally {
        try {
            if (instance != null) {
                clazz.getMethod("release").invoke(instance);
            }
        } catch (Exception ignored) {
        }
    }
    return null;
}

From source file:edu.mit.media.funf.config.DefaultRuntimeTypeAdapterFactory.java

public static boolean isInstantiable(Class<?> type) {
    try {//from  www . ja va2s. c  om
        type.newInstance();
        return true;
    } catch (IllegalAccessException e) {
    } catch (InstantiationException e) {
    }
    return false;
}

From source file:com.judoscript.jamaica.MyUtils.java

public static Object newInstance(String className)
        throws ClassNotFoundException, InstantiationException, IllegalAccessException {
    Class cls = Class.forName(className);
    return cls.newInstance();
}

From source file:jfix.util.Reflections.java

/**
 * Returns a new instance for given clazz.
 *//*from  w  w w  .  j  a v a2  s.  co  m*/
public static Object newInstance(Class<?> clazz) {
    try {
        return clazz.newInstance();
    } catch (Exception e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}

From source file:com.hurence.logisland.classloading.PluginLoader.java

/**
 * Load a plugin by autoproxying between current caller classloader and plugin own classloader.
 *
 * @param className the name of plugin class to load
 * @param <U>       the return type.
 * @return an instance of the requested plugin
 * @throws ClassNotFoundException// w  w w.  j  a  v a 2 s  .c  om
 * @throws InstantiationException
 * @throws IllegalAccessException
 */
public static <U> U loadPlugin(String className)
        throws ClassNotFoundException, InstantiationException, IllegalAccessException {
    ClassLoader cl = registry.get(className);
    if (cl == null) {
        throw new ClassNotFoundException(
                "Unable to find component with class " + className + ". Please check your classpath");
    }
    ClassLoader thiz = Thread.currentThread().getContextClassLoader();
    Object o;
    try {
        Class<?> cls = cl.loadClass(className);
        Thread.currentThread().setContextClassLoader(cl);
        o = cls.newInstance();
    } finally {
        Thread.currentThread().setContextClassLoader(thiz);
    }
    return (U) PluginProxy.create(o);
}

From source file:org.apache.hadoop.mapred.nativetask.testutil.BytesFactory.java

public static Writable newObject(byte[] seed, String className) {
    Writable ret;//from  w w w . ja v a2s  .  c o m
    try {
        Class<?> clazz = Class.forName(className);
        Preconditions.checkArgument(Writable.class.isAssignableFrom(clazz));
        ret = (Writable) clazz.newInstance();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    if (seed != null) {
        updateObject(ret, seed);
    }
    return ret;
}