Results 1 to 1 of 1
-
Create, compile and call a Java source dynamically
The example below creates, compile and call a Java source dynamically.
Java Code: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("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 = { new String(todaySource)}; ByteArrayOutputStream baos= new ByteArrayOutputStream(); new sun.tools.javac.Main(baos,source[0]).compile(source); // if using JDK >= 1.3 then use // public static int com.sun.tools.javac.Main.compile(source); 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(); } } }
Similar Threads
-
How to create object dynamically with class name known in string format
By ranu_gokhe in forum Advanced JavaReplies: 1Last Post: 04-09-2008, 02:15 AM -
Dynamically create a button, but what happened?
By love2java in forum AWT / SwingReplies: 1Last Post: 02-17-2008, 12:01 AM -
How to create widgets dynamically
By sarbuland in forum Advanced JavaReplies: 0Last Post: 02-06-2008, 08:08 PM -
Help with Java Compile File
By baltimore in forum New To JavaReplies: 1Last Post: 08-06-2007, 07:48 AM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks