- import java.io.File;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.PrintWriter;
- import java.lang.reflect.InvocationTargetException;
- import java.lang.reflect.Method;
- import com.sun.tools.javac.*;
- public class MainComplier {
- private static Main javac = new com.sun.tools.javac.Main();
- public static void main(String[] args) throws IOException, ClassNotFoundException,
- SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException,
- InvocationTargetException {
- String classString = "public static void main(String[] args){/n" +
- " System.out.println(/"Hi gal , I love u !!! /");/n" +
- " }/n" +
- "}";
- String path=System.getProperty("user_dir");//获取当前项目路径
- File file=new File(path,"Test.java"); //在当前路径创建空文件
- String filename = file.getName();
- System.out.println("FileName:" + filename);
- int index = filename.indexOf(".");
- String className = filename.substring(0,index); //获取类名
- System.out.println("ClassName:" + className);
- PrintWriter out = new PrintWriter(new FileOutputStream(file)); //在文件里写入代码
- out.println("public class " + className + "{");
- out.println(classString);
- out.flush();
- out.close();
- String[] test = new String[] {"-d", System.getProperty("user.dir"),filename }; //编译命令
- int status = javac.compile(test); //编译代码
- System.out.println("Status:" + status);
- Class myClass = Class.forName("MyFile");//获取.class的实例
- Class[] params=new Class[2]; //将参数的类型描述好
- Integer a=new Integer(10);
- Integer b=new Integer(20);
- params[0]=a.getClass();
- params[1]=a.getClass();
- Method myMethod =myClass.getMethod("add", params);//调用实例中哪个方法
- Object[] myArgs=new Object[2];//将参数的数值设置好
- myArgs[0]=a;
- myArgs[1]=b;
- myMethod.invoke(myClass,myArgs);//调用.class的实例的方法
- }
- }
- import java.io.File;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.PrintWriter;
- public class MyFile {
- public static void main(String[] args) throws IOException {
- String path=System.getProperty("user_dir");
- File file=new File(path,"FileD.txt");
- file.createNewFile();
- PrintWriter out=new PrintWriter(new FileOutputStream(file));
- out.println("hello");
- out.flush();
- out.close();
- System.out.println("sunsnow");
- MyFile test=new MyFile();
- test.add(10, 13);
- }
- public static Integer add(Integer a,Integer b)
- {
- System.out.println(new Integer(a+b));
- return new Integer(a+b);
- }
- }