Here you can find the source of newInstance(Class
Parameter | Description |
---|---|
cls | The class to instantiate. |
T | The type of the class. |
@SuppressWarnings("unchecked") public static <T> T newInstance(Class<T> cls)
//package com.java2s; /*//from w w w . java 2s . co m * AirBlock - Framework for Multi-Platform Minecraft-Plugins. * Copyright (C) 2014 stux! * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ import java.lang.reflect.*; public class Main { /** * Creates a new instance of the class. * @param cls The class to instantiate. * @param <T> The type of the class. * @return The newly instantiated object or {@code null} if the instantiation failed. */ @SuppressWarnings("unchecked") public static <T> T newInstance(Class<T> cls) { Constructor constructor; try { constructor = cls.getConstructor(); } catch (NoSuchMethodException e) { e.printStackTrace(); return null; } if (!constructor.isAccessible()) constructor.setAccessible(true); try { return (T) constructor.newInstance(); } catch (InstantiationException e) { e.printStackTrace(); return null; } catch (IllegalAccessException e) { e.printStackTrace(); return null; } catch (InvocationTargetException e) { e.getCause().printStackTrace(); return null; } } }