Here you can find the source of loadClass(String className, Class
Parameter | Description |
---|---|
T | the desired interface type |
className | the class name that implements the interface |
type | the desired interface |
public static <T> Class<? extends T> loadClass(String className, Class<T> type)
//package com.java2s; /* =================================================================== * ClassUtils.java/* www .ja va 2 s. co m*/ * * Created Jul 15, 2008 8:20:38 AM * * 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 2 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, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA * 02111-1307 USA * =================================================================== * $Id$ * =================================================================== */ public class Main { /** * Load a class of a particular type. * * <p>This uses the {@code type}'s ClassLoader to load the class. If that is * not available, it will use the current thread's context class loader.</p> * * @param <T> the desired interface type * @param className the class name that implements the interface * @param type the desired interface * @return the class */ public static <T> Class<? extends T> loadClass(String className, Class<T> type) { try { ClassLoader loader = type.getClassLoader(); if (loader == null) { loader = Thread.currentThread().getContextClassLoader(); } Class<?> clazz = loader.loadClass(className); if (!type.isAssignableFrom(clazz)) { throw new RuntimeException("Class [" + clazz + "] is not a [" + type + ']'); } return clazz.asSubclass(type); } catch (ClassNotFoundException e) { throw new RuntimeException("Unable to load class [" + className + ']', e); } } }