Java如何将给定的字符串转成Class对象

给定一个定义类的字符串,比如“package com.teasp.compile; public class Test{ public static void main(String[] args){System.out.println(\"compile test.\");} }”,怎么将其转换成Class对象呢?下面的代码可以实现该功能:

/**
 * Java6及以上才可用。
 * 如果ToolProvider.getSystemJavaCompiler();返回的是null,说明jre的lib里面
 * 没有tools.jar,要将jdk的lib中的tools.jar复制到jre的lib中。
 * 设计作者: teasp
 * 信息描述:
 */
public class CompileTest
{
    public final static Class<?> compile(String name, String content)
    {
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
        StrSrcJavaObject srcObject = new StrSrcJavaObject(name, content);
        Iterable<? extends JavaFileObject> fileObjects = Arrays.asList(srcObject);
        String flag = "-d";
        String outDir = System.getProperty("user.dir") + "/bin";
        Iterable<String> options = Arrays.asList(flag, outDir);
        CompilationTask task = compiler.getTask(null, fileManager, null, options, null, fileObjects);
        boolean result = task.call();
        if (result == true)
        {
            System.out.println("Compile it successfully.");
            try
            {
                return Class.forName(name);
            }
            catch (ClassNotFoundException e)
            {
                e.printStackTrace();
            }
            /*ClassLoader loader = CompileTest.class.getClassLoader();
            Class<?> cls;
            try
            {
                cls = loader.loadClass(name);
                return cls;
            }
            catch (ClassNotFoundException e)
            {
                e.printStackTrace();
            }*/
        }
        
        return null;
    }
    
    public static void main(String[] args)
    {
        Class<?> cls = compile("com.teasp.compile.Test",
        		"package com.teasp.compile; public class Test{ public static void main(String[] args){System.out.println(\"compile test.\");} }");
        System.out.println(cls.getCanonicalName());
        try
        {
            Method method = cls.getMethod("main", String[].class);
            System.out.println(method.getName());
            method.invoke(null, new Object[]{new String[]{}});
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    private static class StrSrcJavaObject extends SimpleJavaFileObject
    {
        private String content;
        
        public StrSrcJavaObject(String name, String content)
        {
            super(URI.create("string:///" + name.replace('.', '/') + Kind.SOURCE.extension), Kind.SOURCE);
            this.content = content;
        }
        
        public CharSequence getCharContent(boolean ignoreEncodingErrors)
        {
            return content;
        }
    }
}

 参考:http://www.infoq.com/cn/articles/cf-java-byte-code

你可能感兴趣的:(Java如何将给定的字符串转成Class对象)