Here you can find the source of newInstance(String s)
Parameter | Description |
---|---|
s | fully qualified name of the class to instantiate. |
null
on failure.
public static Object newInstance(String s)
//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; } } }