Java Class New Instance newInstance(String s)

Here you can find the source of newInstance(String s)

Description

Creates a new instance of the given class.

License

Apache License

Parameter

Parameter Description
s fully qualified name of the class to instantiate.

Return

the new instance or null on failure.

Declaration

public static Object newInstance(String s) 

Method Source Code

//package com.java2s;
/*/*from w w w .  j  a v a  2s  . c o m*/
 *  Copyright 2005-2006 Stefan Reuter
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class Main {
    /**
     * Creates a new instance of the given class. The class is loaded using the current thread's context
     * class loader and instantiated using its default constructor.
     *
     * @param s fully qualified name of the class to instantiate.
     * @return the new instance or <code>null</code> on failure.
     */
    public static Object newInstance(String s) {
        final ClassLoader classLoader = Thread.currentThread().getContextClassLoader();

        try {
            Class clazz = classLoader.loadClass(s);
            Constructor constructor = clazz.getConstructor();
            return constructor.newInstance();
        } catch (ClassNotFoundException e) {
            return null;
        } catch (IllegalAccessException e) {
            return null;
        } catch (InstantiationException e) {
            return null;
        } catch (NoSuchMethodException e) {
            // no default constructor
            return null;
        } catch (InvocationTargetException e) {
            // constructor threw an exception
            return null;
        }
    }
}

Related

  1. newInstance(String clazzStr)
  2. newInstance(String cls, Class interfaceType)
  3. newInstance(String klass)
  4. newInstance(String name)
  5. newInstance(String name, ClassLoader loader)
  6. newInstance(String type)
  7. newInstance(String type, Class cast)
  8. newInstance(T obj)
  9. newInstance(T obj, Class argType, Object arg)