To run an external class file in a Java program

Source: Internet
Author: User
Tags exit command line implement reflection thread advantage
The program runs an external class file in a Java program











One, Introduction


whether it is programming in a traditional programming language (C + +, VB, etc.) or in the Java language, it is often necessary to execute another independent external program in a running program. For example, to design an IDE program in Java, the IDE program must be able to tune and run other independent external Java programs. Besides, it is also an important means to improve the efficiency of program development to directly run the existing external program to realize some specific functions of this program.


JAVA2 provides two solutions for implementing an external class file (that is, a Java program) that runs in a Java program, running an external class file in the same process and running an external class file in a different process.


second, run the external class file in the same process


Java stipulates that any Java application (application) entry is: Main (), so to implement running the external class file in the same process, just try to call the main () method of the external class file directly in the program.

The image (Reflection) API in
JAVA2 can be used for classes in Java virtual machines, interfaces, objects and so on, through it can dynamically get the classes, interfaces, objects of various information, but also can dynamically set the value of the object's domain, and can dynamically invoke various methods in the object.


Therefore, we can use the reflection API to dynamically determine the main () method of an external class file at run time (runtime), and then call it. For example:


assumes that the external class file (Invoked.java) to be executed is as follows:


public class invoked {


public static void Main (string[] args) {


if (args.length!= 2) {


System.err.println ("Usage:java invoked name Sex");


system.exit (1);


}


System.out.println ("Hello, I come from outclassfile!");


System.out.println ("My name is" +args[0]);


System.out.println ("My Sex Is" +args[1]);


}


}


The main program that runs the above class file (Invoker.java) generally has the following form:


import java.lang.reflect.*;


public class Invoker {


public static void Main (string[] args) {


//args[0] Stores the name of the external class being executed, in this case args[0]= "invoked"


if (args.length!= 1) {


System.err.println ("Usage:java invoker");


system.exit (1);


}


class[] argtypes = new Class[1];


argtypes[0] = String[].class;


try {


Method Mainmethod = Class.forName (Args[0]). Getdeclaredmethod ("main", argtypes);


object[] Arglistforinvokedmain = new Object[1];

The number of arguments for the
//invoked main () method = 1


arglistforinvokedmain[0] = new STRING[2];


The parameter of the called Main () method is a string array of length 2


String argstoinvoked[]={"Wangshuanglin", "Man"};


arglistforinvokedmain[0]= argstoinvoked;


//sets the parameters passed to the main () method of the invoked external class


Mainmethod.invoke (null, arglistforinvokedmain);


//inkoke (Object obj, object[] args) is the calling method;


//Where obj is the object instance of the method; But because the main () here is a static method,


//So no need to instantiate, fill in null;


//args is the argument passed to the method.


}


catch (ClassNotFoundException ex) {


System.err.println ("Class" +args[0]+ "not found in classpath.");


}


catch (Nosuchmethodexception ex) {


System.err.println ("Class" +args[0]+ "does not define public static void Main (string[))";


}


catch (InvocationTargetException ex) {


System.err.println ("Exception while executing" +args[0]+ ":" +ex.gettargetexception ());


}


catch (Illegalaccessexception ex) {


System.err.println ("Main (string[]) in class" +args[0] + "are not public");


}


}


}


runs the main program with the following command line: Java invoker invoked.


This example simply shows how to execute external class files in the same process (processes), not only, but also in the same thread (thread), which of course can be done in different threads.


three, run an external class file in a different process


to run an external class file in a different process, just try to do it directly in the program:


Java External class file (in this case: Java invoked).


Fortunately, the Java.lang.Runtime class provides a exce () method to complete a call to an external executable program. Note: Here the Exce () method calls the Java interpreter, the executable, and the external class file Invoked.class is simply a parameter that appears as a Java interpreter. In fact, the Exce () method can also invoke other executable files directly, not just the Java interpreter.


assumes that the external class file to be executed is still the invoked.java above;


The main program that runs the above class file (Invokerfromseparateprocess.java) is as follows:


public class Invokerfromseparateprocess {


public static void Main (string[] args) {


if (args.length!= 1) {


System.err.println ("Usage:java invokerfromseparateprocess");


system.exit (1);


}


String name= "Wangshuanglin";


String sex= "Mans";


try {


Process p = runtime.getruntime (). EXEC ("Java" +args[0]+name+sex);


}


catch (Java.io.IOException ex) {


System.err.println ("Problems invoking Class" +args[0]+ ":" +ex);


}


}


}


runs the main program with the following command line: Java invokerfromseparateprocess invoked.


you may find that you do not see the output of the called external class file Invoked.class. The problem is that the standard output stream (porcess) of the new process (standard output stream) is not automatically directed to stdout. In order to get and display the output information of the new process, we can use P.getinputstream () to read the output information of the new process, and then send the read information to the standard output stream (standard outputs).


Four, the conclusion


uses the image (Reflection) API in Java2 to implement methods for executing external class files in the same process (process), with the advantage that it consumes less resources because it does not open new processes; It is powerful because it can execute not only the main () method of the external class file, It is also possible to perform other methods of external class files and to take advantage of all the resources of external class files in a very meticulous manner. The disadvantage is that it can only execute the external class files written in Java, and can not execute other forms of executable files, such as EXE, COM and so on, and secondly, programming is slightly more complex than the second form.


The Java.lang.Runtime class provides a exce () method to complete calls to external executable programs, with the advantage of being simple to program and running all executable programs, including programs written in other languages. The disadvantage is that it consumes more resources because it wants to open a new process, and then it can run only the external class file as a whole, but not the internal resources of the invoked program in detail.


in general, if you want to run an external class file written in Java, choosing the first method is more flexible and appropriate; If you want to run an executable program written in another language, it is convenient and straightforward to choose the second method, but generally try to avoid doing so, otherwise it will reduce the cross-platform nature of the Java program , because this external program is generally platform-dependent.














Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.