java获取class的几种方式

以获取Hello.class为例

public class Hello {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        System.out.println("tes22t2");
        for (String arg : args)
        {
            System.out.println("hello proms:" + arg);
        }

    }
}

1.反射

public static void main(String[] args) throws Exception
    {
        args = new String[]{"Hello","java疯狂讲义w"};
        String progClass = args[0];
        String[] progArgs = new String[args.length-1];
        System.arraycopy(args , 1 , progArgs, 0 , progArgs.length);
//        URL[] urls = {new URL("file:")};
//        Class<?> clazz = (new URLClassLoader(urls)).loadClass(progClass);
        Class<?> clazz = Class.forName(progClass);
        // 获取需要运行的类的主方法
        Method main = clazz.getMethod("main" , (new String[0]).getClass());
        Object[] argsArray = {progArgs};
        main.invoke(null,argsArray);
    }

2.URLClassLoader

URL[] urls = {new URL("file:")};
Class<?> clazz = (new URLClassLoader(urls)).loadClass(progClass);

3.loadClass

CompileClassLoader ccl = new CompileClassLoader();
		// 加载需要运行的类
		Class<?> clazz = ccl.loadClass(progClass);

4.覆写findClass

参考

java8--类加载机制与反射(java疯狂讲义3复习笔记)  

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

posted @ 2017-07-17 13:34  lakeslove  阅读(4234)  评论(0编辑  收藏  举报