1, 可以通过 Reflection 机制来做. (推荐)
2, 可以通过比如比较 servlet 的版本号来做, 这样不好.

解决方案 »

  1.   

    import java.io.*;
    import java.util.*;
    import java.lang.reflect.*;public class MakeTodayClass {
      Date today = new Date();
      String todayMillis = Long.toString(today.getTime());
      String todayClass = "z_" + todayMillis;
      String todaySource = todayClass + ".java";
      
      public static void main (String args[]){
        MakeTodayClass mtc = new MakeTodayClass();
        mtc.createIt();
        if (mtc.compileIt()) {
          System.out.println("Running " + mtc.todayClass + ":\n\n");
          mtc.runIt();
          }
        else
          System.out.println(mtc.todaySource + " is bad.");
        }  public void createIt() {
        try {
          FileWriter aWriter = new FileWriter(todaySource, true);
          //aWriter.write("package com;");
          aWriter.write("public class "+ todayClass + "{");
          aWriter.write(" public void doit() {");
          aWriter.write(" System.out.println(\""+todayMillis+"\");");
          aWriter.write(" }}\n");
          aWriter.flush();      
          aWriter.close();
          }
        catch(Exception e){
          e.printStackTrace();
          }
        }
      
      public boolean compileIt() {
        String [] source = {"-d","d:/",new String(todaySource) };
        ByteArrayOutputStream baos= new ByteArrayOutputStream();    //new sun.tools.javac.Main(baos,source[0]).compile(source);    
        // if using JDK >= 1.3 then use
        System.out.println(com.sun.tools.javac.Main.compile(source));    
        System.out.println("================"+new String(baos.toByteArray()));
        return (baos.toString().indexOf("error")==-1);
        }
        
      public void runIt() {
        try {
          Class params[] = {};
          Object paramsObj[] = {};
          Class thisClass = Class.forName(todayClass);
          Object iClass = thisClass.newInstance();
          Method thisMethod = thisClass.getDeclaredMethod("doit", params);
          thisMethod.invoke(iClass, paramsObj);
          }
        catch (Exception e) {
          e.printStackTrace();
          }
        }
    }
      

  2.   

    谢谢你的例子。俺的jdk突然出了故障,helloworld死活运行不了。让我重新装好再试试看你的样例。