Dynamically generate Java code (2)

zhaozj2021-02-12  193

/ *? * Create a date 2004-7-2? * Create a human hongsoft? * File name testcompile.java?*/package com.hongsoft.test;

Import java.io. *;

// Customized class equipment PUBLIC CLASS TESTCOMPILE EXTENDS CLASSLOADER {? String _compiler;? String _classpath

? public static void main (string [] args)? {

?? new testcompile () ;?}

PUBLIC TESTCOMPILE ()? {?? super (classloader.getsystemclassloader ()); ?? // Default compiler ?? IF (_compiler == null) ??? _ compiler = "d: //j2sdk1.4.2//bin // javac ";

?? _ classpath = "."; ?? String extraclasspath = ??? "" c: // program files // java // j2re1.4.2 // =/ rT.jar "; ?? // = system.getProperty "Calc.classPath"); ?? IF (extraclasspath! = null) ?? {??? _ classpath = ???? _ classpath ????? system.getproperty ("path.separator") ????? EXTRACLASSPATH; ??} ?? compile () ;?}

PUBLIC VOID Compile ()? {??????? String filename = ""; ?? string classname = ""; ?? Try ?? {??? // created a temporary file ??? file javafile =? ??? File.createTempfile ("Compiled_", ".java", new file (".")); ??? filename = javafile.getname (); ??? ClassName = filename.substring (0, FileName.lastIndexof (".")); ??? GENERATEJAVAFILE (JAVAFILE, CLASSNAME); ??? // Compiling files ??? InvokeCompiler (javafile); ??? // Create a Java class ??? Byte [] buf = readbytes Classname ".class"); ??? class c = defineclass (buf, 0, buf.length); ??? Try ??? {??????? c.newinstance (); ???} ? ??????? {???? throw new runtimeException (E.GetMessage ()); ???} ??? Catch (instantiationException e) ??? {???? throw new runtimeException (E.GETMESSAGE ()); ???} ??} ?? Catch (IOException E) ?? {??? throw new runtimeException (E.GetMessage ()); ??}?}

? // generated java file void generateJavaFile (File javafile, String classname) throws IOException {?? FileOutputStream out = new FileOutputStream (javafile);?? ?? String text = ??? "public class" ???? classname? ??? "{" ???? "public int getcreater () {return 1;}" ???? "}";? out.write ()); ?? OUT. Close ();?}? // Compile Java file? Void invokecompiler (file javafile) throws ooException? {?? string [] cmd = ??? {_compiler, "-classpath", _classpath, javafile.getname ()}; ?? // Execute the compile command ?? // a1: ?? process process = runtime.getruntime (). EXEC (cmd); ?? Try ?? {// Wait for the compiler to end ??? Process.waitfor (); ??} ?? carat (interruptedException e) {??} ?? int val = process.exitvalue (); ?? IF (Val! = 0) ?? {??? throw new runtimeException ("Compiling error: " " Error code " VAL); ??}?

? // read the class file in a Byte array? Byte [] readbytes (String filename) throws ooException? {??? file classfile = new file (filename); ?? Byte [] buf = new byte [(int) ClassFile .leinputstream in = new fileInputstream (ClassFile); ?? in.close (); ?? Return buf ;?}

}

转载请注明原文地址:https://www.9cbs.com/read-7225.html

New Post(0)