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.yunmel.syncretic.utils.commons.CollectionsUtils.java

/**
 * copy list?//w w  w  .j  ava2  s.c  om
 * 
 * @param source ?list
 * @param destinationClass 
 * @return
 */
public static <E> List<E> copyTo(List<?> source, Class<E> destinationClass) {
    if (source.size() == 0)
        return Collections.emptyList();
    List<E> res = new ArrayList<E>();
    try {
        for (Object o : source) {
            E e = destinationClass.newInstance();
            BeanUtils.copyProperties(e, o);
            res.add(e);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    return res;
}

From source file:kina.utils.UtilMongoDB.java

/**
 * converts from BsonObject to an entity class with kina's anotations
 *
 * @param classEntity the entity name.//from ww  w.j  a v a 2  s. co  m
 * @param bsonObject  the instance of the BSONObjet to convert.
 * @param <T>         return type.
 * @return the provided bsonObject converted to an instance of T.
 * @throws IllegalAccessException
 * @throws InstantiationException
 * @throws InvocationTargetException
 */
public static <T> T getObjectFromBson(Class<T> classEntity, BSONObject bsonObject)
        throws IllegalAccessException, InstantiationException, InvocationTargetException {
    T t = classEntity.newInstance();

    Field[] fields = filterKinaFields(classEntity);

    Object insert;

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

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

        Object currentBson = bsonObject.get(kinaFieldName(field));
        if (currentBson != null) {

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

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

            } else if (KinaType.class.isAssignableFrom(classField)) {
                insert = getObjectFromBson(classField, (BSONObject) bsonObject.get(kinaFieldName(field)));
            } else {
                insert = currentBson;
            }

            method.invoke(t, insert);
        }
    }

    return t;
}

From source file:com.tealeaf.plugin.PluginEvent.java

public static void init(Context context) {
    if (initialized) {
        return;//from  w w w. j a  v  a  2s.co m
    }
    initialized = true;
    ArrayList<String> classNames = new ArrayList<String>();

    try {
        String apkName = null;

        try {
            apkName = context.getPackageManager()
                    .getApplicationInfo(context.getApplicationContext().getPackageName(), 0).sourceDir;
        } catch (NameNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        DexFile dexFile = new DexFile(new File(apkName));
        Enumeration<String> enumeration = dexFile.entries();

        int pluginsPackageStrLen = PLUGINS_PACKAGE_NAME.length();

        while (enumeration.hasMoreElements()) {
            String className = enumeration.nextElement();

            if (className.length() < pluginsPackageStrLen)
                continue;

            if (!className.contains("$")) {
                if (className.subSequence(0, pluginsPackageStrLen).equals(PLUGINS_PACKAGE_NAME)) {
                    classNames.add(className);
                }
            }
        }
    } catch (IOException e) {
        logger.log(e);
    }

    if (classNames.size() > 0) {
        String[] classNamesArr = new String[classNames.size()];
        classNames.toArray(classNamesArr);

        for (String name : classNamesArr) {
            try {
                Class objcls = Class.forName(name);

                if (IPlugin.class.isAssignableFrom(objcls)) {
                    Object instance = objcls.newInstance();

                    if (instance != null) {
                        logger.log("{plugins} Instantiated:", name);
                        classMap.put(name, instance);
                    } else {
                        logger.log("{plugins} WARNING: Class not found:", name);
                    }
                } else {
                    logger.log("{plugins} Ignoring class that does not derive from IPlugin:", name);
                }
            } catch (ClassNotFoundException e) {
                logger.log("{plugins} WARNING: Class not found:", name);
                e.printStackTrace();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }

        }
    }
}

From source file:Main.java

private static int getStatusBarHeight(Activity activity) {
    Class<?> c;
    Object obj;//from w w  w  .ja v a  2  s  .c om
    Field field;
    int x;
    int statusBarHeight = 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());
        statusBarHeight = activity.getResources().getDimensionPixelSize(x);
    } catch (Exception e1) {
        e1.printStackTrace();
    }
    return statusBarHeight;
}

From source file:at.ait.dme.magicktiler.MagickTilerCLI.java

private static boolean showGui(String... args) {
    boolean displayGui = false;
    try {//from w  w  w  .  j a  v  a2  s  . c  o m
        if (displayGui = Arrays.asList(args).contains("-g")) {
            // the gui can be removed from the build, which is why 
            // we try to load it dynamically here.
            Class<?> gui = Class.forName("at.ait.dme.magicktiler.gui.MagickTilerGUI");
            Method startup = gui.getMethod("startup", new Class[] { String[].class });
            startup.invoke(gui.newInstance(), new Object[] { args });
        }
    } catch (Exception e) {
        System.err.println("Failed to start GUI (did you exclude it from the build?): " + e);
    }
    return displayGui;
}

From source file:clearUp.Collections3.java

/**
 * copy list// w  w w.  j a  va  2  s . c o m
* @param source list
* @param destinationClass 
* @return
 */
public static <E> List<E> copyTo(List<?> source, Class<E> destinationClass) {
    if (source.size() == 0)
        return Collections.emptyList();
    List<E> res = new ArrayList<E>(source.size());
    try {
        for (Object o : source) {
            E e = destinationClass.newInstance();
            BeanUtils.copyProperties(e, o);
            res.add(e);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    return res;
}

From source file:com.netsteadfast.greenstep.util.ManualDataSourceFactory.java

public static DataSource getDataSource(Class<?> dataSourceClass, String url, String user, String password)
        throws Exception {
    if (!checkDataSourceClass(dataSourceClass)) {
        throw new Exception("DataSource Class is not implements DataSource. error!");
    }//w ww . j  a  v  a2 s .c  om
    if (StringUtils.isBlank(url) || StringUtils.isBlank(user)) {
        throw new Exception("url or user is required!");
    }
    DataSource ds = (DataSource) dataSourceClass.newInstance();
    Ognl.setValue("url", ds, url);
    Ognl.setValue("user", ds, user);
    Ognl.setValue("password", ds, (null == password ? "" : password));
    return ds;
}

From source file:com.taobao.tddl.common.DynamicLog.java

private static LogBuilder createBuilder(String script) {
    GroovyClassLoader loader = new GroovyClassLoader(DynamicLog.class.getClassLoader());
    String groovyScript = completeGroovy(script);
    Class<?> c_groovy;
    try {/*from   w w w  . j  a  v a2  s.c om*/
        c_groovy = loader.parseClass(groovyScript);
    } catch (CompilationFailedException e) {
        throw new IllegalArgumentException(groovyScript, e);
    }

    try {
        // 
        return (LogBuilder) c_groovy.newInstance();
    } catch (Throwable t) {
        throw new IllegalArgumentException("", t);
    }
}

From source file:com.lonepulse.robozombie.response.Deserializers.java

/**
 * <p>Retrieves the {@link AbstractDeserializer} which is defined for the given {@link Class}.</p>
 * //from   w w  w. j av a  2 s. c  o m
 * @param deserializerType
 *          the {@link Class} whose implementation of {@link AbstractDeserializer} is retrieved
 * <br><br>
 * @return the implementation of {@link AbstractDeserializer} for the given {@link Class}
 * <br><br>
 * @throws DeserializerInstantiationException
 *          if a custom deserializer failed to be instantiated using its <b>default constructor</b> 
 * <br><br>
 * @since 1.3.0
 */
public static final AbstractDeserializer<?> resolve(Class<? extends AbstractDeserializer<?>> deserializerType) {

    try {

        synchronized (DESERIALIZERS) {

            String key = deserializerType.getName();

            AbstractDeserializer<?> deserializer = DESERIALIZERS.get(key);

            if (deserializer == null) {

                deserializer = deserializerType.newInstance();
                DESERIALIZERS.put(key, deserializer);
            }

            return deserializer;
        }
    } catch (Exception e) {

        throw new DeserializerInstantiationException(deserializerType, e);
    }
}

From source file:com.myee.tarot.core.classloader.ThreadLocalManager.java

public static <T> ThreadLocal<T> createThreadLocal(final Class<T> type, final boolean createInitialValue) {
    ThreadLocal<T> response = new ThreadLocal<T>() {
        @Override/*from  w w w . j a  v  a 2  s  .c o  m*/
        protected T initialValue() {
            addThreadLocal(this);
            if (!createInitialValue) {
                return null;
            }
            try {
                return type.newInstance();
            } catch (InstantiationException e) {
                throw new RuntimeException(e);
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            }
        }

        @Override
        public void set(T value) {
            super.get();
            super.set(value);
        }
    };
    return response;
}