Example usage for java.lang ClassLoader loadClass

List of usage examples for java.lang ClassLoader loadClass

Introduction

In this page you can find the example usage for java.lang ClassLoader loadClass.

Prototype

public Class<?> loadClass(String name) throws ClassNotFoundException 

Source Link

Document

Loads the class with the specified binary name.

Usage

From source file:com.acciente.induction.init.ControllerResolverInitializer.java

public static ControllerResolver getControllerResolver(Config.ControllerResolver oControllerResolverConfig,
        Config.ControllerMapping oControllerMappingConfig, ModelPool oModelPool, ClassLoader oClassLoader,
        ServletConfig oServletConfig)//from  ww  w  . j av a  2s.c om
        throws ClassNotFoundException, InvocationTargetException, ConstructorNotFoundException,
        ParameterProviderException, IllegalAccessException, InstantiationException, IOException {
    ControllerResolver oControllerResolver;
    String sControllerResolverClassName;
    Log oLog;

    oLog = LogFactory.getLog(ControllerResolverInitializer.class);

    sControllerResolverClassName = oControllerResolverConfig.getClassName();

    if (Strings.isEmpty(sControllerResolverClassName)) {
        oControllerResolver = new ShortURLControllerResolver(oControllerMappingConfig, oClassLoader);
    } else {
        oLog.info("loading user-defined controller resolver: " + sControllerResolverClassName);

        Class oControllerResolverClass = oClassLoader.loadClass(sControllerResolverClassName);

        // attempt to find and call the single public constructor
        oControllerResolver = (ControllerResolver) ObjectFactory.createObject(oControllerResolverClass,
                new Object[] { oServletConfig, oControllerResolverConfig, oControllerMappingConfig,
                        oClassLoader },
                new InitializerParameterProvider(oModelPool, "controller-resolver-init"));
    }

    return oControllerResolver;
}

From source file:jef.tools.reflect.ClassEx.java

/**
 * ?//w w w .  ja va 2  s . c  o  m
 * 
 * @param className
 * @param loder
 * @return
 * @throws ReflectionException
 */
public static final ClassEx getClassEx(String className, ClassLoader loder) throws ReflectionException {
    try {
        if (loder == null)
            loder = ClassEx.class.getClassLoader();
        Class<?> c = loder.loadClass(className);
        return new ClassEx(c);
    } catch (ClassNotFoundException e) {
        throw new ReflectionException(e, "Class: " + className + " not found.");
    }
}

From source file:Main.java

public static Class<?> findClass(String name) {
    ClassLoader cl;
    try {/*from  w  w w.j a v a 2  s .  c  o  m*/
        cl = Thread.currentThread().getContextClassLoader();
    } catch (SecurityException e) {
        cl = null;
    }

    Map<String, Class<?>> map;
    synchronized (cache) {
        map = cache.get(cl);

        if (map == null) {
            map = new LinkedHashMap<String, Class<?>>(16, 0.75f, true) {
                private static final long serialVersionUID = 1L;

                protected boolean removeEldestEntry(Map.Entry<String, Class<?>> eldest) {
                    return size() > 1024;
                };
            };
            cache.put(cl, map);
        }
    }
    synchronized (map) {
        if (!map.containsKey(name)) {
            Class<?> target;
            try {
                if (cl != null) {
                    target = cl.loadClass(name);
                } else {
                    target = Class.forName(name);
                }
            } catch (ClassNotFoundException e) {
                target = null;
            }
            map.put(name, target);
        }
        return map.get(name);
    }
}

From source file:com.helpinput.core.Utils.java

@SuppressWarnings("unchecked")
public static <T> T newInstance(Object caller, String className, Object... args) {
    try {/* www.ja v a2s .  c om*/
        ClassLoader loader = (caller instanceof ClassLoader) ? (ClassLoader) caller
                : caller.getClass().getClassLoader();
        return (T) newInstance(loader.loadClass(className), args);
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
        return null;
    }
}

From source file:com.acciente.induction.init.TemplatingEngineInitializer.java

public static TemplatingEngine getTemplatingEngine(Config.Templating oTemplatingConfig, ModelPool oModelPool,
        ClassLoader oClassLoader, ServletConfig oServletConfig)
        throws ClassNotFoundException, IOException, InvocationTargetException, ConstructorNotFoundException,
        ParameterProviderException, IllegalAccessException, InstantiationException {
    TemplatingEngine oTemplatingEngine;//from w w  w  .  j  a v a2  s  . c  om
    String sTemplatingEngineClassName;
    Log oLog;

    oLog = LogFactory.getLog(TemplatingEngineInitializer.class);

    sTemplatingEngineClassName = oTemplatingConfig.getTemplatingEngine().getClassName();

    if (Strings.isEmpty(sTemplatingEngineClassName)) {
        // if no templating engine is configured use the freemarker engine as the default
        oTemplatingEngine = new FreemarkerTemplatingEngine(oTemplatingConfig, oClassLoader, oServletConfig);
    } else {
        oLog.info("loading user-defined templating engine: " + sTemplatingEngineClassName);

        Class oTemplatingEngineClass = oClassLoader
                .loadClass(oTemplatingConfig.getTemplatingEngine().getClassName());

        oTemplatingEngine = (TemplatingEngine) ObjectFactory.createObject(oTemplatingEngineClass,
                new Object[] { oServletConfig, oTemplatingConfig, oClassLoader },
                new InitializerParameterProvider(oModelPool, "templating-engine-init"));
    }

    return oTemplatingEngine;
}

From source file:com.springframework.beans.BeanUtils.java

/**
 * Find a JavaBeans PropertyEditor following the 'Editor' suffix convention
 * (e.g. "mypackage.MyDomainClass" -> "mypackage.MyDomainClassEditor").
 * <p>Compatible to the standard JavaBeans convention as implemented by
 * {@link java.beans.PropertyEditorManager} but isolated from the latter's
 * registered default editors for primitive types.
 * @param targetType the type to find an editor for
 * @return the corresponding editor, or {@code null} if none found
 *///from  ww w.ja  va 2  s .  c  o m
public static PropertyEditor findEditorByConvention(Class<?> targetType) {
    if (targetType == null || targetType.isArray() || unknownEditorTypes.contains(targetType)) {
        return null;
    }
    ClassLoader cl = targetType.getClassLoader();
    if (cl == null) {
        try {
            cl = ClassLoader.getSystemClassLoader();
            if (cl == null) {
                return null;
            }
        } catch (Throwable ex) {
            // e.g. AccessControlException on Google App Engine
            if (logger.isDebugEnabled()) {
                logger.debug("Could not access system ClassLoader: " + ex);
            }
            return null;
        }
    }
    String editorName = targetType.getName() + "Editor";
    try {
        Class<?> editorClass = cl.loadClass(editorName);
        if (!PropertyEditor.class.isAssignableFrom(editorClass)) {
            if (logger.isWarnEnabled()) {
                logger.warn("Editor class [" + editorName
                        + "] does not implement [java.beans.PropertyEditor] interface");
            }
            unknownEditorTypes.add(targetType);
            return null;
        }
        return (PropertyEditor) instantiateClass(editorClass);
    } catch (ClassNotFoundException ex) {
        if (logger.isDebugEnabled()) {
            logger.debug("No property editor [" + editorName + "] found for type " + targetType.getName()
                    + " according to 'Editor' suffix convention");
        }
        unknownEditorTypes.add(targetType);
        return null;
    }
}

From source file:com.contrastsecurity.cassandra.migration.utils.FeatureDetector.java

private boolean isPresent(String className, ClassLoader classLoader) {
    try {//w  w w  .  j a  v a2s  .co m
        classLoader.loadClass(className);
        return true;
    } catch (Throwable ex) {
        // Class or one of its dependencies is not present...
        return false;
    }
}

From source file:com.jeeframework.util.classes.ClassUtils.java

/**
 * Check whether the given class is visible in the given ClassLoader.
 * @param clazz the class to check (typically an interface)
 * @param classLoader the ClassLoader to check against (may be <code>null</code>,
 * in which case this method will always return <code>true</code>)
 *///w  w  w  .  j  av a  2s .  c  om
public static boolean isVisible(Class clazz, ClassLoader classLoader) {
    if (classLoader == null) {
        return true;
    }
    try {
        Class actualClass = classLoader.loadClass(clazz.getName());
        return (clazz == actualClass);
        // Else: different interface class found...
    } catch (ClassNotFoundException ex) {
        // No interface class found...
        return false;
    }
}

From source file:org.nebulaframework.core.job.archive.GridArchive.java

/**
 * Returns the {@code GridJob} classes with in the given {@code .nar} file.
 * Uses {@link GridArchiveClassLoader}.//from  w w  w .  j av  a2 s.  c  om
 * 
 * @param file
 *            {@code File} instance for {@code .nar} file.
 * 
 * @return Fully qualified class names of {@code GridJob} classes in the
 *         file.
 * 
 * @throws IOException
 *             if occurred during File I/O operations
 * 
 * @see GridArchiveClassLoader
 */
protected static String[] findJobClassNames(final File file) throws IOException {

    // Instantiate ClassLoader for given File
    ClassLoader classLoader = AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
        public GridArchiveClassLoader run() {
            return new GridArchiveClassLoader(file);
        }

    });

    // Find ClassNames of all classes inside the file (except in NEBULA-INF)
    // Content inside .jar files will not be processed
    String[] allClassNames = getAllClassNames(file);

    // Holds Class<?> instances loaded by ClassLoader, for all classes
    List<String> jobClassNames = new ArrayList<String>();

    for (String className : allClassNames) {
        try {
            // Load each Class and check if its a GridJob Class
            if (isGridJobClass(classLoader.loadClass(className))) {
                jobClassNames.add(className);
            }
        } catch (ClassNotFoundException e) {
            // Log and continue with rest
            log.debug("[GridArchive] Unable to load class " + className);
        }
    }
    return jobClassNames.toArray(new String[] {});
}

From source file:com.jeeframework.util.classes.ClassUtils.java

/**
 * Replacement for <code>Class.forName()</code> that also returns Class instances
 * for primitives (like "int") and array class names (like "String[]").
 * @param name the name of the Class/*from  www. ja  v a 2  s .c  o m*/
 * @param classLoader the class loader to use
 * (may be <code>null</code>, which indicates the default class loader)
 * @return Class instance for the supplied name
 * @throws ClassNotFoundException if the class was not found
 * @throws LinkageError if the class file could not be loaded
 * @see Class#forName(String, boolean, ClassLoader)
 */
public static Class forName(String name, ClassLoader classLoader) throws ClassNotFoundException, LinkageError {
    Assert.notNull(name, "Name must not be null");

    Class clazz = resolvePrimitiveClassName(name);
    if (clazz != null) {
        return clazz;
    }

    // "java.lang.String[]" style arrays
    if (name.endsWith(ARRAY_SUFFIX)) {
        String elementClassName = name.substring(0, name.length() - ARRAY_SUFFIX.length());
        Class elementClass = forName(elementClassName, classLoader);
        return Array.newInstance(elementClass, 0).getClass();
    }

    // "[Ljava.lang.String;" style arrays
    int internalArrayMarker = name.indexOf(INTERNAL_ARRAY_PREFIX);
    if (internalArrayMarker != -1 && name.endsWith(";")) {
        String elementClassName = null;
        if (internalArrayMarker == 0) {
            elementClassName = name.substring(INTERNAL_ARRAY_PREFIX.length(), name.length() - 1);
        } else if (name.startsWith("[")) {
            elementClassName = name.substring(1);
        }
        Class elementClass = forName(elementClassName, classLoader);
        return Array.newInstance(elementClass, 0).getClass();
    }

    ClassLoader classLoaderToUse = classLoader;
    if (classLoaderToUse == null) {
        classLoaderToUse = getDefaultClassLoader();
    }
    return classLoaderToUse.loadClass(name);
}