Get the Class from the class name. - Java Reflection

Java examples for Reflection:Class

Description

Get the Class from the class name.

Demo Code


//package com.java2s;

import java.security.AccessController;
import java.security.PrivilegedAction;

public class Main {
    /**//from w w w. j  a  v a2  s.  c  o m
     * Get the Class from the class name.
     * <p>
     * The context class loader will be utilized if accessible and non-null.
     * Otherwise the defining class loader of this class will
     * be utilized.
     *
     * @param name the class name.
     * @return the Class, otherwise null if the class cannot be found.
     */
    public static Class classForName(String name) {
        return classForName(name, getContextClassLoader());
    }

    /**
     * Get the Class from the class name.
     *
     * @param name the class name.
     * @param cl the class loader to use, if null then the defining class loader
     * of this class will be utilized.
     * @return the Class, otherwise null if the class cannot be found.
     */
    public static Class classForName(String name, ClassLoader cl) {
        if (cl != null) {
            try {
                return Class.forName(name, false, cl);
            } catch (ClassNotFoundException ex) {
            }
        }
        try {
            return Class.forName(name);
        } catch (ClassNotFoundException ex) {
        }

        return null;
    }

    /**
     * Get the context class loader.
     *
     * @return the context class loader, otherwise null security privilages
     *         are not set.
     */
    public static ClassLoader getContextClassLoader() {
        return AccessController
                .doPrivileged(new PrivilegedAction<ClassLoader>() {
                    public ClassLoader run() {
                        ClassLoader cl = null;
                        try {
                            cl = Thread.currentThread()
                                    .getContextClassLoader();
                        } catch (SecurityException ex) {
                        }
                        return cl;
                    }
                });
    }
}

Related Tutorials