java写个.java文件,自己编译,自己加载执行HelloWorld

package classloader.compile;


import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;


public class Demo1 {


public static void main(String[] args) throws IOException, ClassNotFoundException, NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
File claFile = new File("i:/Hello.class");
if(claFile.exists()) {
System.out.println("发现.class文件存在,开始删除");
boolean d = claFile.delete();
if(d) {
System.out.println("删除成功");
}else {
System.out.println("删除失败,请手动删除");
System.exit(0);
}
}
File javaF = new File("i:/Hello.java");
createJavaFile(javaF);
compileJavaToClass(claFile, javaF);
runClassFile(args);
}


@SuppressWarnings("deprecation")
private static void runClassFile(String[] args) throws MalformedURLException, ClassNotFoundException,
NoSuchMethodException, IllegalAccessException, InvocationTargetException {
File url = new File("i:/");
String path = url.toURL().toString();
@SuppressWarnings("resource")
URLClassLoader loader = new URLClassLoader(new URL[] {new URL(path)});
Class claz = loader.loadClass("Hello");
Method main = claz.getMethod("main", String[].class);
main.invoke(null, (Object)args);
}


private static void compileJavaToClass(File claFile, File javaF) throws FileNotFoundException, IOException {
String command = "javac i:/Hello.java";
try {
Process process = Runtime.getRuntime().exec(command);
process.waitFor();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
}
if(claFile.exists()) {
System.out.println("检测到.class文件,编译成功");
}else {
System.out.println("没有检车到.class文件,编译失败");
System.exit(0);
}
}


private static void createJavaFile(File javaF) throws FileNotFoundException {
if(javaF.exists()) {
System.out.println("发现.java文件存在,开始删除");
boolean d = javaF.delete();
if(d) {
System.out.println("删除成功");
}else {
System.out.println("删除失败,请手动删除");
System.exit(0);
}
}
PrintWriter pWriter  = new PrintWriter(javaF);
pWriter.println("public class Hello {");
pWriter.println("public static void main(String[] args){");
pWriter.println("System.out.println(\"Hello \");");
pWriter.println("}}");
pWriter.flush();
pWriter.close();
if(javaF.exists()) {
System.out.println(".java文件创建成功");
}else {
System.out.println(".java 创建失败");
System.exit(0);
}
}


}

你可能感兴趣的:(java,基础,java类加载器,java编译)