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.xidu.framework.common.util.Utils.java

public static Object copyDomain(Object origDomain, Class<?> domainClass) {
    if (null == origDomain) {
        return null;
    }/*from   w ww  .  ja  v a  2 s  . com*/
    Object dest = null;
    try {
        dest = domainClass.newInstance();
        ConvertUtils.register(new DateConverter(null), Date.class);
        BeanUtils.copyProperties(dest, origDomain);
    } catch (Exception e) {
        return null;
    }
    return dest;
}

From source file:com.aol.advertising.qiao.util.ContextUtils.java

public static Object createBean(String className) throws ClassNotFoundException {
    //logger.info("loading " + className + "...");
    Object o = null;//from w  w  w .ja v  a 2 s .c o m

    logger.info("Instantiate the class " + className);
    Class<?> clz = Class.forName(className);
    try {
        o = clz.newInstance();
    } catch (Exception e) {
        logger.error("Failed to instantiate class " + className);
    }

    return o;
}

From source file:com.funtl.framework.smoke.core.modules.sys.utils.quartz.TaskUtils.java

/**
 * ??scheduleJob//from  w w w  .j  ava  2 s  .co m
 *
 * @param taskJob
 */
public static void invokMethod(TaskJob taskJob) {
    Object object = null;
    Class clazz = null;
    if (StringUtils.isNotBlank(taskJob.getTaskJobSpring())) {
        object = SpringContextHolder.getBean(taskJob.getTaskJobSpring());
    } else if (StringUtils.isNotBlank(taskJob.getTaskJobBean())) {
        try {
            clazz = Class.forName(taskJob.getTaskJobBean());
            object = clazz.newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    if (object == null) {
        logger.error("?? = [" + taskJob.getTaskJobName()
                + "]---------------???????");
        return;
    }
    clazz = object.getClass();
    Method method = null;
    try {
        method = clazz.getDeclaredMethod(taskJob.getTaskJobMethod());
    } catch (NoSuchMethodException e) {
        logger.error("?? = [" + taskJob.getTaskJobName()
                + "]---------------???????");
    } catch (SecurityException e) {
        e.printStackTrace();
    }
    if (method != null) {
        try {
            method.invoke(object);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
    logger.debug("?? = [" + taskJob.getTaskJobName() + "]----------??");
}

From source file:org.mule.providers.soap.axis.wsdl.wsrf.util.AdviceAdderHelper.java

/**
 * Get Advice from .aspect package and create for each Advice class instance an
 * Advisor with mapped name "*extend"./*  ww w . j  a  v  a 2  s.  c  o  m*/
 * 
 * @return A List of Advisor.
 */
private static List getListAdvisorClass() {
    List advisors = new LinkedList();

    try {
        Class[] listClassAdvice = getClasses("org.mule.providers.soap.axis.wsdl.wsrf.aspect");
        Class advice = null;
        Advisor advisor = null;
        for (int i = 0; i < listClassAdvice.length; i++) {
            advice = listClassAdvice[i];
            try {

                advisor = new NameMatchMethodPointcutAdvisor((Advice) advice.newInstance());

            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            if (advisor != null) {
                ((NameMatchMethodPointcut) advisor).setMappedName(MAPPED_NAME);
                advisors.add(advisor);

            }

        }
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
    return advisors;
}

From source file:grails.plugin.searchable.internal.lucene.LuceneUtils.java

/**
 * Returns a list of terms by analysing the given text
 *
 * @param text the text to analyse//from w w  w  .  j a  v a 2 s  .  c  o m
 * @param analyzerClass the Analyzer class to use, may be null in which case Lucene's StandardAnalyzer is used
 * @return a list of text terms
 */
public static String[] termsForText(String text, Class analyzerClass) {
    if (analyzerClass == null) {
        return termsForText(text, (Analyzer) null);
    }
    try {
        return termsForText(text, (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:de.betterform.connector.ConnectorFactory.java

/**
 * Returns a new connector factory loaded from configuration
 *
 * @return A new connector factory/*from ww  w.  j  a  va 2  s  . c  o  m*/
 * @throws XFormsConfigException If a configuration error occurs
 */
public static ConnectorFactory getFactory() throws XFormsConfigException {
    ConnectorFactory factory;
    String className = Config.getInstance().getConnectorFactory();

    if (className == null || className.equals("")) {
        factory = new DefaultConnectorFactory();
    } else {
        try {
            Class clazz = Class.forName(className, true, ConnectorFactory.class.getClassLoader());

            factory = (ConnectorFactory) clazz.newInstance();
        } catch (ClassNotFoundException cnfe) {
            throw new XFormsConfigException(cnfe);
        } catch (ClassCastException cce) {
            throw new XFormsConfigException(cce);
        } catch (InstantiationException ie) {
            throw new XFormsConfigException(ie);
        } catch (IllegalAccessException iae) {
            throw new XFormsConfigException(iae);
        }
    }

    return factory;

}

From source file:com.laxser.blitz.util.BlitzBeanUtils.java

public static Object instantiateClass(@SuppressWarnings("rawtypes") Class clazz)
        throws BeanInstantiationException {
    // spring's : Object mappedObject = BeanUtils.instantiateClass(this.mappedClass);
    // lama's : private Object instantiateClass(this.mappedClass);
    // why: ??mappedClass.newInstranceBeanUtils.instantiateClass(mappedClass)1?
    try {//from  w  w w  . jav  a2  s  .co  m
        return clazz.newInstance();
    } catch (Exception ex) {
        throw new BeanInstantiationException(clazz, ex.getMessage(), ex);
    }
}

From source file:io.apiman.cli.util.MappingUtil.java

/**
 * Return an instance of {@code destinationClass} with a copy of identical fields to those found
 * in {@code source}.// w  ww.  j  a  v  a2 s  .  c o m
 *
 * @param source           the source object
 * @param destinationClass the return type Class definition
 * @param <D>              the return type
 * @param <S>              the source type
 * @return an instance of {@code destinationClass} containing the copied fields
 */
public static <S, D> D map(S source, Class<D> destinationClass) {
    try {
        /*
         * Explicitly instantiate the destination to avoid ModelMapper returning the source object
         * in cases where the destination type is assignable from the source type.
         */
        final D destination = destinationClass.newInstance();

        MODEL_MAPPER.map(source, destination);

        return destination;

    } catch (InstantiationException | IllegalAccessException e) {
        throw new RuntimeException(e);
    }
}

From source file:bs.java

private static void loadable(String filename) {
    File file = new File(filename);

    JarInputStream is;/* ww w . ja  v  a 2  s  .  c  o  m*/
    try {
        ClassLoader loader = URLClassLoader.newInstance(new URL[] { file.toURI().toURL() });
        is = new JarInputStream(new FileInputStream(file));
        JarEntry entry;
        while ((entry = is.getNextJarEntry()) != null) {
            if (entry.getName().endsWith(".class") && !entry.getName().contains("/")) {
                Class<?> cls = Class.forName(FilenameUtils.removeExtension(entry.getName()), false, loader);
                for (Class<?> i : cls.getInterfaces()) {
                    if (i.equals(Loadable.class)) {
                        Loadable l = (Loadable) cls.newInstance();
                        Bs.addModule(l);
                    }
                }
            }
        }
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }

}

From source file:com.dsj.core.beans.CollectionFactory.java

/**
 * Create the most approximate map for the given map class.
 * <p>Tries to create the given map class. If that fails, a TreeMap or
 * linked Map will be used as fallback for a SortedMap or Map, respectively.
 * @param mapClass the original map class
 * @param initialCapacity the initial capacity
 * @return the new collection instance/*from   w  w  w.  j  a  v  a 2  s  .  c o  m*/
 * @see java.util.ArrayList
 * @see java.util.TreeSet
 * @see #createLinkedSetIfPossible
 */
public static Map createApproximateMap(Class mapClass, int initialCapacity) {
    Assert.notNull(mapClass, "Map class must not be null");
    if (!mapClass.isInterface()) {
        try {
            return (Map) mapClass.newInstance();
        } catch (Exception ex) {
            logger.debug("Could not instantiate map type [" + mapClass.getName() + "]: " + ex.getMessage());
        }
    }
    if (SortedMap.class.isAssignableFrom(mapClass)) {
        return new TreeMap();
    } else {
        return createLinkedMapIfPossible(initialCapacity);
    }
}