public class running{
public static void main(string[] args){
System.out.println("helloworld");
////////////////////////////////在此行调入waiting程序并且编译,动态运行
}
}
我另外有一个程序,存在硬盘中,是.java文件,该程序若如下
public class waitting{
public static void main(string[] args){
System.out.println("how are you ");
}
}
如何达到运行running的时候又编译而且运行waiting
12 个解决方案
#1
一种方式:可以通过java.lang.Runtime和java.lang.Process调用windows的cmd命命令实现你的要求;
另一种:通过ant构建工具,这个好像离你的要求比较远,呵呵。
另一种:通过ant构建工具,这个好像离你的要求比较远,呵呵。
#2
我看网上有很多说是用动态编译和动态运行实现的,具体的是怎样的?
#3
这个问题貌似我以前又答过!!如果你能看得明白我以前修改过这个例子,你就明白了!!!!!
import java.io.DataInputStream;
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 java.net.URL;
import java.net.URLClassLoader;
/**
* @author Every E-mail/MSN:mwgjkf@hotmail.com
* QQ:30130942
* @version 创建时间:Dec 30, 2008 3:34:57 PM
* 类说明:
*
*/
public class RuntimeCode{
/**编译器*/
private static com.sun.tools.javac.Main javac=new com.sun.tools.javac.Main();
/**等待用户输入JavaCode,然后编译、执行*/
public static void main(String[] args) throws Exception{
String code = "";
DataInputStream bd = new DataInputStream(System.in);
byte[] brray= new byte[200];
int i = bd.read(brray);
code = new String(brray,0,i);
run(compile(code));
System.out.println(code);
}
/**编译JavaCode,返回临时文件对象*/
private synchronized static File compile(String code)throws IOException,Exception{
File file;
//在用户当前文件目录创建一个临时代码文件
file=File.createTempFile("JavaCode",".java",new File(System.getProperty("user.dir")));
//当虚拟机退出时,删除此临时java源文件
file.deleteOnExit();
//获得文件名和类名字
String filename=file.getName();
String classname=getClassName(filename);
System.out.println(classname);
//将代码输出到文件
PrintWriter out=new PrintWriter(new FileOutputStream(file));
out.write("public class "+classname+"{"+"public static void main(String []agrs) "+"{");
out.write(code);
out.write("}}");
//关闭文件流
out.flush();
out.close();
//编译代码文件
String[] args=new String[]{"-d",System.getProperty("user.dir"),filename};
System.out.println("user.dir-------->"+System.getProperty("user.dir"));
//返回编译的状态代码
int status=javac.compile(args);
//处理编译状态
System.out.println(status);
return file;
}
public void main(){
}
/**执行刚刚编译的类文件*/
private static synchronized void run(File file){
//当虚拟机退出时,删除此临时编译的类文件
//获得文件名和类名字
String filename = file.getName();
String classname = getClassName(filename);
System.out.println("filename-------->"+filename);
System.out.println("classname----"+classname);
new File(file.getParent(),classname+".class").deleteOnExit();
try {
// 访问这个类
//Class cls = Class.forName(classname);
URL url = new URL("file:/"+System.getProperty("user.dir")+""+File.separator);
URLClassLoader urlClass = new URLClassLoader(new URL[]{url});
Class cls = urlClass.loadClass(classname);
Object obj = cls.newInstance();
System.out.println("obj==========="+obj);
//调用main方法
Method main = cls.getMethod("main", new Class[] {String[].class });
main.invoke(obj, new Object[] {new String[]{} });
}catch (SecurityException se) {
debug("access to the information is denied:" + se.toString());
}catch (NoSuchMethodException nme) {
debug("a matching method is not found or if then name is or : " + nme.toString());
}catch (InvocationTargetException ite) {
debug("Exception in main: " + ite.getTargetException());
}catch (Exception e){
debug(e.toString());
e.printStackTrace();
}
}
/**打印调试信息*/
private static void debug(String msg){
System.err.println(msg);
}
/**根据一个java源文件名获得类名*/
private static String getClassName(String filename){
return filename.substring(0,filename.length()-5);
}
}
动态编译用:com.sun.tools.javac.Main javac这个类!
动态加载不在classPath的类用:URLClassLoader这个类,class.forName个人认为只能加载在CLASSPATH的类!!
动态运行JAVA类用JAVA反射机制!!!!
以上都有,慢慢消化!!!!!!!
import java.io.DataInputStream;
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 java.net.URL;
import java.net.URLClassLoader;
/**
* @author Every E-mail/MSN:mwgjkf@hotmail.com
* QQ:30130942
* @version 创建时间:Dec 30, 2008 3:34:57 PM
* 类说明:
*
*/
public class RuntimeCode{
/**编译器*/
private static com.sun.tools.javac.Main javac=new com.sun.tools.javac.Main();
/**等待用户输入JavaCode,然后编译、执行*/
public static void main(String[] args) throws Exception{
String code = "";
DataInputStream bd = new DataInputStream(System.in);
byte[] brray= new byte[200];
int i = bd.read(brray);
code = new String(brray,0,i);
run(compile(code));
System.out.println(code);
}
/**编译JavaCode,返回临时文件对象*/
private synchronized static File compile(String code)throws IOException,Exception{
File file;
//在用户当前文件目录创建一个临时代码文件
file=File.createTempFile("JavaCode",".java",new File(System.getProperty("user.dir")));
//当虚拟机退出时,删除此临时java源文件
file.deleteOnExit();
//获得文件名和类名字
String filename=file.getName();
String classname=getClassName(filename);
System.out.println(classname);
//将代码输出到文件
PrintWriter out=new PrintWriter(new FileOutputStream(file));
out.write("public class "+classname+"{"+"public static void main(String []agrs) "+"{");
out.write(code);
out.write("}}");
//关闭文件流
out.flush();
out.close();
//编译代码文件
String[] args=new String[]{"-d",System.getProperty("user.dir"),filename};
System.out.println("user.dir-------->"+System.getProperty("user.dir"));
//返回编译的状态代码
int status=javac.compile(args);
//处理编译状态
System.out.println(status);
return file;
}
public void main(){
}
/**执行刚刚编译的类文件*/
private static synchronized void run(File file){
//当虚拟机退出时,删除此临时编译的类文件
//获得文件名和类名字
String filename = file.getName();
String classname = getClassName(filename);
System.out.println("filename-------->"+filename);
System.out.println("classname----"+classname);
new File(file.getParent(),classname+".class").deleteOnExit();
try {
// 访问这个类
//Class cls = Class.forName(classname);
URL url = new URL("file:/"+System.getProperty("user.dir")+""+File.separator);
URLClassLoader urlClass = new URLClassLoader(new URL[]{url});
Class cls = urlClass.loadClass(classname);
Object obj = cls.newInstance();
System.out.println("obj==========="+obj);
//调用main方法
Method main = cls.getMethod("main", new Class[] {String[].class });
main.invoke(obj, new Object[] {new String[]{} });
}catch (SecurityException se) {
debug("access to the information is denied:" + se.toString());
}catch (NoSuchMethodException nme) {
debug("a matching method is not found or if then name is or : " + nme.toString());
}catch (InvocationTargetException ite) {
debug("Exception in main: " + ite.getTargetException());
}catch (Exception e){
debug(e.toString());
e.printStackTrace();
}
}
/**打印调试信息*/
private static void debug(String msg){
System.err.println(msg);
}
/**根据一个java源文件名获得类名*/
private static String getClassName(String filename){
return filename.substring(0,filename.length()-5);
}
}
动态编译用:com.sun.tools.javac.Main javac这个类!
动态加载不在classPath的类用:URLClassLoader这个类,class.forName个人认为只能加载在CLASSPATH的类!!
动态运行JAVA类用JAVA反射机制!!!!
以上都有,慢慢消化!!!!!!!
#4
反射可以做到
#5
最简单的就是都先编译好,且在两个类中都写main方法,执行其中一个类时再调用另一个类的main就可以了
#6
顶
#7
3楼,你的程序我用jcreator编译运行的时候出现
--------------------配置: <--------------------
Usage: java [-options] class [args...]
(to execute a class)
or java [-options] -jar jarfile [args...]
(to execute a jar file)
where options include:
-client to select the "client" VM
-server to select the "server" VM
-hotspot is a synonym for the "client" VM [deprecated]
The default VM is client.
-cp <class search path of directories and zip/jar files>
-classpath <class search path of directories and zip/jar files>
A ; separated list of directories, JAR archives,
and ZIP archives to search for class files.
-D<name>=<value>
set a system property
-verbose[:class|gc|jni]
enable verbose output
-version print product version and exit
-version:<value>
require the specified version to run
-showversion print product version and continue
-jre-restrict-search | -jre-no-restrict-search
include/exclude user private JREs in the version search
-? -help print this help message
-X print help on non-standard options
-ea[:<packagename>...|:<classname>]
-enableassertions[:<packagename>...|:<classname>]
enable assertions
-da[:<packagename>...|:<classname>]
-disableassertions[:<packagename>...|:<classname>]
disable assertions
-esa | -enablesystemassertions
enable system assertions
-dsa | -disablesystemassertions
disable system assertions
-agentlib:<libname>[=<options>]
load native agent library <libname>, e.g. -agentlib:hprof
see also, -agentlib:jdwp=help and -agentlib:hprof=help
-agentpath:<pathname>[=<options>]
load native agent library by full pathname
-javaagent:<jarpath>[=<options>]
load Java programming language agent, see java.lang.instrument
处理已完成。
--------------------配置: <--------------------
Usage: java [-options] class [args...]
(to execute a class)
or java [-options] -jar jarfile [args...]
(to execute a jar file)
where options include:
-client to select the "client" VM
-server to select the "server" VM
-hotspot is a synonym for the "client" VM [deprecated]
The default VM is client.
-cp <class search path of directories and zip/jar files>
-classpath <class search path of directories and zip/jar files>
A ; separated list of directories, JAR archives,
and ZIP archives to search for class files.
-D<name>=<value>
set a system property
-verbose[:class|gc|jni]
enable verbose output
-version print product version and exit
-version:<value>
require the specified version to run
-showversion print product version and continue
-jre-restrict-search | -jre-no-restrict-search
include/exclude user private JREs in the version search
-? -help print this help message
-X print help on non-standard options
-ea[:<packagename>...|:<classname>]
-enableassertions[:<packagename>...|:<classname>]
enable assertions
-da[:<packagename>...|:<classname>]
-disableassertions[:<packagename>...|:<classname>]
disable assertions
-esa | -enablesystemassertions
enable system assertions
-dsa | -disablesystemassertions
disable system assertions
-agentlib:<libname>[=<options>]
load native agent library <libname>, e.g. -agentlib:hprof
see also, -agentlib:jdwp=help and -agentlib:hprof=help
-agentpath:<pathname>[=<options>]
load native agent library by full pathname
-javaagent:<jarpath>[=<options>]
load Java programming language agent, see java.lang.instrument
处理已完成。
#8
看了看,走了
#9
可以用包这个方法吗,不过要先把程序编译成.class文件,再导包才行,
#10
XUEXUE
#11
将被调用这编译成可执行程序,再使用二楼的第一种方法即可。二楼使用ant的方法和楼主的要求是不相符的。
#12
小弟看了不知所云,也多看看受教了
#1
一种方式:可以通过java.lang.Runtime和java.lang.Process调用windows的cmd命命令实现你的要求;
另一种:通过ant构建工具,这个好像离你的要求比较远,呵呵。
另一种:通过ant构建工具,这个好像离你的要求比较远,呵呵。
#2
我看网上有很多说是用动态编译和动态运行实现的,具体的是怎样的?
#3
这个问题貌似我以前又答过!!如果你能看得明白我以前修改过这个例子,你就明白了!!!!!
import java.io.DataInputStream;
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 java.net.URL;
import java.net.URLClassLoader;
/**
* @author Every E-mail/MSN:mwgjkf@hotmail.com
* QQ:30130942
* @version 创建时间:Dec 30, 2008 3:34:57 PM
* 类说明:
*
*/
public class RuntimeCode{
/**编译器*/
private static com.sun.tools.javac.Main javac=new com.sun.tools.javac.Main();
/**等待用户输入JavaCode,然后编译、执行*/
public static void main(String[] args) throws Exception{
String code = "";
DataInputStream bd = new DataInputStream(System.in);
byte[] brray= new byte[200];
int i = bd.read(brray);
code = new String(brray,0,i);
run(compile(code));
System.out.println(code);
}
/**编译JavaCode,返回临时文件对象*/
private synchronized static File compile(String code)throws IOException,Exception{
File file;
//在用户当前文件目录创建一个临时代码文件
file=File.createTempFile("JavaCode",".java",new File(System.getProperty("user.dir")));
//当虚拟机退出时,删除此临时java源文件
file.deleteOnExit();
//获得文件名和类名字
String filename=file.getName();
String classname=getClassName(filename);
System.out.println(classname);
//将代码输出到文件
PrintWriter out=new PrintWriter(new FileOutputStream(file));
out.write("public class "+classname+"{"+"public static void main(String []agrs) "+"{");
out.write(code);
out.write("}}");
//关闭文件流
out.flush();
out.close();
//编译代码文件
String[] args=new String[]{"-d",System.getProperty("user.dir"),filename};
System.out.println("user.dir-------->"+System.getProperty("user.dir"));
//返回编译的状态代码
int status=javac.compile(args);
//处理编译状态
System.out.println(status);
return file;
}
public void main(){
}
/**执行刚刚编译的类文件*/
private static synchronized void run(File file){
//当虚拟机退出时,删除此临时编译的类文件
//获得文件名和类名字
String filename = file.getName();
String classname = getClassName(filename);
System.out.println("filename-------->"+filename);
System.out.println("classname----"+classname);
new File(file.getParent(),classname+".class").deleteOnExit();
try {
// 访问这个类
//Class cls = Class.forName(classname);
URL url = new URL("file:/"+System.getProperty("user.dir")+""+File.separator);
URLClassLoader urlClass = new URLClassLoader(new URL[]{url});
Class cls = urlClass.loadClass(classname);
Object obj = cls.newInstance();
System.out.println("obj==========="+obj);
//调用main方法
Method main = cls.getMethod("main", new Class[] {String[].class });
main.invoke(obj, new Object[] {new String[]{} });
}catch (SecurityException se) {
debug("access to the information is denied:" + se.toString());
}catch (NoSuchMethodException nme) {
debug("a matching method is not found or if then name is or : " + nme.toString());
}catch (InvocationTargetException ite) {
debug("Exception in main: " + ite.getTargetException());
}catch (Exception e){
debug(e.toString());
e.printStackTrace();
}
}
/**打印调试信息*/
private static void debug(String msg){
System.err.println(msg);
}
/**根据一个java源文件名获得类名*/
private static String getClassName(String filename){
return filename.substring(0,filename.length()-5);
}
}
动态编译用:com.sun.tools.javac.Main javac这个类!
动态加载不在classPath的类用:URLClassLoader这个类,class.forName个人认为只能加载在CLASSPATH的类!!
动态运行JAVA类用JAVA反射机制!!!!
以上都有,慢慢消化!!!!!!!
import java.io.DataInputStream;
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 java.net.URL;
import java.net.URLClassLoader;
/**
* @author Every E-mail/MSN:mwgjkf@hotmail.com
* QQ:30130942
* @version 创建时间:Dec 30, 2008 3:34:57 PM
* 类说明:
*
*/
public class RuntimeCode{
/**编译器*/
private static com.sun.tools.javac.Main javac=new com.sun.tools.javac.Main();
/**等待用户输入JavaCode,然后编译、执行*/
public static void main(String[] args) throws Exception{
String code = "";
DataInputStream bd = new DataInputStream(System.in);
byte[] brray= new byte[200];
int i = bd.read(brray);
code = new String(brray,0,i);
run(compile(code));
System.out.println(code);
}
/**编译JavaCode,返回临时文件对象*/
private synchronized static File compile(String code)throws IOException,Exception{
File file;
//在用户当前文件目录创建一个临时代码文件
file=File.createTempFile("JavaCode",".java",new File(System.getProperty("user.dir")));
//当虚拟机退出时,删除此临时java源文件
file.deleteOnExit();
//获得文件名和类名字
String filename=file.getName();
String classname=getClassName(filename);
System.out.println(classname);
//将代码输出到文件
PrintWriter out=new PrintWriter(new FileOutputStream(file));
out.write("public class "+classname+"{"+"public static void main(String []agrs) "+"{");
out.write(code);
out.write("}}");
//关闭文件流
out.flush();
out.close();
//编译代码文件
String[] args=new String[]{"-d",System.getProperty("user.dir"),filename};
System.out.println("user.dir-------->"+System.getProperty("user.dir"));
//返回编译的状态代码
int status=javac.compile(args);
//处理编译状态
System.out.println(status);
return file;
}
public void main(){
}
/**执行刚刚编译的类文件*/
private static synchronized void run(File file){
//当虚拟机退出时,删除此临时编译的类文件
//获得文件名和类名字
String filename = file.getName();
String classname = getClassName(filename);
System.out.println("filename-------->"+filename);
System.out.println("classname----"+classname);
new File(file.getParent(),classname+".class").deleteOnExit();
try {
// 访问这个类
//Class cls = Class.forName(classname);
URL url = new URL("file:/"+System.getProperty("user.dir")+""+File.separator);
URLClassLoader urlClass = new URLClassLoader(new URL[]{url});
Class cls = urlClass.loadClass(classname);
Object obj = cls.newInstance();
System.out.println("obj==========="+obj);
//调用main方法
Method main = cls.getMethod("main", new Class[] {String[].class });
main.invoke(obj, new Object[] {new String[]{} });
}catch (SecurityException se) {
debug("access to the information is denied:" + se.toString());
}catch (NoSuchMethodException nme) {
debug("a matching method is not found or if then name is or : " + nme.toString());
}catch (InvocationTargetException ite) {
debug("Exception in main: " + ite.getTargetException());
}catch (Exception e){
debug(e.toString());
e.printStackTrace();
}
}
/**打印调试信息*/
private static void debug(String msg){
System.err.println(msg);
}
/**根据一个java源文件名获得类名*/
private static String getClassName(String filename){
return filename.substring(0,filename.length()-5);
}
}
动态编译用:com.sun.tools.javac.Main javac这个类!
动态加载不在classPath的类用:URLClassLoader这个类,class.forName个人认为只能加载在CLASSPATH的类!!
动态运行JAVA类用JAVA反射机制!!!!
以上都有,慢慢消化!!!!!!!
#4
反射可以做到
#5
最简单的就是都先编译好,且在两个类中都写main方法,执行其中一个类时再调用另一个类的main就可以了
#6
顶
#7
3楼,你的程序我用jcreator编译运行的时候出现
--------------------配置: <--------------------
Usage: java [-options] class [args...]
(to execute a class)
or java [-options] -jar jarfile [args...]
(to execute a jar file)
where options include:
-client to select the "client" VM
-server to select the "server" VM
-hotspot is a synonym for the "client" VM [deprecated]
The default VM is client.
-cp <class search path of directories and zip/jar files>
-classpath <class search path of directories and zip/jar files>
A ; separated list of directories, JAR archives,
and ZIP archives to search for class files.
-D<name>=<value>
set a system property
-verbose[:class|gc|jni]
enable verbose output
-version print product version and exit
-version:<value>
require the specified version to run
-showversion print product version and continue
-jre-restrict-search | -jre-no-restrict-search
include/exclude user private JREs in the version search
-? -help print this help message
-X print help on non-standard options
-ea[:<packagename>...|:<classname>]
-enableassertions[:<packagename>...|:<classname>]
enable assertions
-da[:<packagename>...|:<classname>]
-disableassertions[:<packagename>...|:<classname>]
disable assertions
-esa | -enablesystemassertions
enable system assertions
-dsa | -disablesystemassertions
disable system assertions
-agentlib:<libname>[=<options>]
load native agent library <libname>, e.g. -agentlib:hprof
see also, -agentlib:jdwp=help and -agentlib:hprof=help
-agentpath:<pathname>[=<options>]
load native agent library by full pathname
-javaagent:<jarpath>[=<options>]
load Java programming language agent, see java.lang.instrument
处理已完成。
--------------------配置: <--------------------
Usage: java [-options] class [args...]
(to execute a class)
or java [-options] -jar jarfile [args...]
(to execute a jar file)
where options include:
-client to select the "client" VM
-server to select the "server" VM
-hotspot is a synonym for the "client" VM [deprecated]
The default VM is client.
-cp <class search path of directories and zip/jar files>
-classpath <class search path of directories and zip/jar files>
A ; separated list of directories, JAR archives,
and ZIP archives to search for class files.
-D<name>=<value>
set a system property
-verbose[:class|gc|jni]
enable verbose output
-version print product version and exit
-version:<value>
require the specified version to run
-showversion print product version and continue
-jre-restrict-search | -jre-no-restrict-search
include/exclude user private JREs in the version search
-? -help print this help message
-X print help on non-standard options
-ea[:<packagename>...|:<classname>]
-enableassertions[:<packagename>...|:<classname>]
enable assertions
-da[:<packagename>...|:<classname>]
-disableassertions[:<packagename>...|:<classname>]
disable assertions
-esa | -enablesystemassertions
enable system assertions
-dsa | -disablesystemassertions
disable system assertions
-agentlib:<libname>[=<options>]
load native agent library <libname>, e.g. -agentlib:hprof
see also, -agentlib:jdwp=help and -agentlib:hprof=help
-agentpath:<pathname>[=<options>]
load native agent library by full pathname
-javaagent:<jarpath>[=<options>]
load Java programming language agent, see java.lang.instrument
处理已完成。
#8
看了看,走了
#9
可以用包这个方法吗,不过要先把程序编译成.class文件,再导包才行,
#10
XUEXUE
#11
将被调用这编译成可执行程序,再使用二楼的第一种方法即可。二楼使用ant的方法和楼主的要求是不相符的。
#12
小弟看了不知所云,也多看看受教了