Start java application from java program

My problem is the following:
I start a java application A that allows you to select a couple of .java files.
After having choosen them, the application adds some additional information to these .java files (that means some more lines of code � we call it �infecting� the java files).
After the files have been infected, I want to start the application B implemented by these choosen and infected .java-files (without a new start of the Java Virtual Machine)
For doing so, we use the following method whichs works quite fine:
public static void ExecuteWithInvoke(String path, String classname)
     try
          new URLClassLoader(new URL[] {new File(path).toURL()})
               .loadClass(classname).getMethod("main",
               new Class[] { String[].class }).invoke(null,
               new Object[] { new String[] {} });
     catch (Exception e)
     {e.printStackTrace();}
The only problem that occurs:
When the application B is launched, the �old� version of the choosen .java files is used and not the current, already infected version of these files. (I guess because the �old� .class files are used.)
I solved this problem by finishing the program A after the infecting and restart my application B manually. In this case the infected .java files are used (I guess the new Start of the Java Virtual Machine solves my problem by reloading the �new� .class files)
How can I reach to start my application with the mentioned method but with the infected .java files and without having a new start of the JVM ??
Can anybody help me?
Thanks in advance
Sorry for my English, it�s a long time since I quit school

Hello,
my problem of reloading classes is still unsolved although you tried to help me!
Therefore I posted a little program to illustrate our difficulty.
It would be nice if somebody could have a look at this program.
We have a file Testdatei.java whose only method is the main method.
I get the class object of this file and with the help of Reflection the declared methods.
Evereything works fine so far.
Then I change the content of this file by adding an additional method a() (see change() for this).
Now I delete the old class file and I compile Testdatei.java again (see compileJava()) and once more I get the class object for this changed file. Afterwards I get the declared methods for this class via reflection.
But instead of showing now the methods main() and a() Reflection still only shows the method main().
I guess the changed class has not been reloaded!!
package testpackage;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import com.sun.tools.javac.Main;
public class LoadClass
     private File f;
     private Class c = null;
     private Object o;
     public LoadClass()
          f = new File("C:/AAJ/src/testpackage/Testdatei.java");
          try
               o = neuesExemplar(f.getPath(), "testpackage.Testdatei");
               c = o.getClass();
               System.out.println("Class " + c.getName() + " found.");
          catch (Exception e)
          {e.printStackTrace();}
          Method [] method = c.getDeclaredMethods();
          for (int i=0; i<method.length; i++)
               System.out.println(method.getName());
          change();          
          compileJava(f.getPath());
          File fileToDelete = new File("bin/testpackage/Testdatei.class");
          System.out.println(fileToDelete.delete());
          Class cla = null;
          try
               Object o = neuesExemplar(f.getPath(), "testpackage.Testdatei");
               cla = o.getClass();
               System.out.println("Class " + cla.getName() + " found.");
          catch (Exception e)
          {e.printStackTrace();}
          Method [] methods = cla.getDeclaredMethods();
          for (int i=0; i<methods.length; i++)
               System.out.println(methods[i].getName());
     private int compileJava(String javaFile)
     String[] args = {"-d", "C:/AAJ/bin/", "-classpath", System.getProperty("java.class.path"), javaFile};
     return Main.compile(args);
     public static void main(String[] args)
          new LoadClass();
     private Object neuesExemplar(String pfad, String klassename) throws Exception
     URL url = new File(pfad).toURL();
     URLClassLoader cl = new URLClassLoader( new URL[]{ url });
     Class c = cl.loadClass(klassename);
     return c.newInstance();
     private void change()
          FileWriter fw;
          BufferedWriter bw;
          try
               fw = new FileWriter(f);
               bw = new BufferedWriter(fw);               
               bw.write("package testpackage;");
               bw.newLine();
               bw.newLine();
               bw.write("public class Testdatei");
               bw.newLine();
               bw.write("{");
               bw.newLine();
               bw.write("public static void main (String [] args)");
               bw.newLine();
               bw.write("{");
               bw.write("System.out.println(4);");
               bw.newLine();
               bw.write("}");
               bw.newLine();
               bw.newLine();
               bw.write("private void a ()");
               bw.newLine();
               bw.write("{");
               bw.newLine();
               bw.write("System.out.println(55);");
               bw.newLine();
               bw.write("}");
               bw.newLine();
               bw.write("}");
               bw.close();
               fw.close();               
          catch (IOException e)
          {e.printStackTrace();}                                             
I�m using eclipse 3.1.0. Is it possible that it�s a bug in eclipse that eclipse holds the old class file in memory from the beginning and always refers to this one and not to the new compiled one?
Thanks a lot
Simon

Similar Messages

  • Start JavaFX application from Java

    Hello,
    I have the following scenario:
    I have a small JavaFX application and a big Java application. Now the Java App should call the JavaFX App to start up.
    Further the JavaFX App has to call some methods from the Java App. Is this possible?
    What is the best approach for my scenario?
    Maybe somebody has made some experiences ..
    thanks!
    Edited by: 799878 on 03.11.2010 07:54

    "Now the Java App should call the JavaFX App to start up."
    I'm assuming that the JavaFX code and the Java code are in the same application, correct? If so, then there are hacks available, but no standard way to start up JavaFX from Java will exist until the APIs have been ported from JavaFX script to Java.
    "Further the JavaFX App has to call some methods from the Java App. Is this possible?"
    Yes. Java can be called from JavaFX just fine. Just be careful if you use multi-threading or time consuming operations, since JavaFX script is apparently single threaded. Also be aware that netbeans normally compiles JavaFX applications with JSE version 1.5, so library features that did not exist until later versions will not be available by default.

  • Executing a Java application from JAVA

    Hello all,
    I have a problem spawning a Java IRC client from another Java application. The client only manages to execute itself properly [join a specific channel] once the original parent application has been closed. Any ideas?
    The code is as follows:
    public void run(){
         String[] cmd = {"java", "IRC"};
         try {
               Process p = Runtime.getRuntime().exec(cmd);
              p.waitFor();
         } catch (Exception exc){
              print ("Could not run the IRC session file" + exc);
      }

    Well, if you ask me, it's not very good Java style to try to access the command line to run ANOTHER Java application.
    My suggestion is simply call the IRC program's methods to get it started. Don't bother with Runtime.exec.

  • How to execute a java application from java itself

    Hi,
    I�m working in Client Server environment. After starting the server, i want to automatically call the client. ( java Server (in Server.java
    the call (java Client) has to be done. Can anyone help me for this problem.
    thanks.

    In normal client server design the client initiates communication with the server, not the other way around.
    So you initiate a conversation just like a normal client server communication.
    -The client is running.
    -The client listens for a connection (SocketServer)
    -The server starts up.
    -It connects to the client using a socket. (The server must know the host/ip of the client.)

  • How do I start and suspend Java Application from say C++ program

    I want to start a Java application via C++ and on some condition i want to suspend the same program not terminate , but suspend

    Have you tried running the virtual machine from your C++ application ? You can start Java applications from your C++ application using JNI after starting the Virtual machine from within your C++ application. According to the Java documentation you can even now stop the virtual machine from within your C++ program.
    I haven't looked at the 'suspend' detail but I suppose it will not be a problem to call a method via JNI to set a flag to suspend a thread etc.
    There is a tutorial: 'Invoking the Java Virtual Machine' at the following URL: http://java.sun.com/docs/books/tutorial/native1.1/invoking/invo.html.
    This example seems to work only for version1.1 of the JDK. For JDK1.3, version 1.2, (I am not so sure whether I fully understand Sun's version numbers for Java yet) there is some updates on the JNI for starting the VM from C++. This article is called 'JNI Enhancements'. The URL for this article is:
    http://java.sun.com/j2se/1.3.0/docs/guide/jni/jni-12.html
    You have to set version to: JNI_VERSION_1_2
    There is only one problem. I get an error when calling JNI_CreateJavaVM from C++. I could not find any documentation that indicates how you can go about diagnosing what is causing the problem. Normally in Visual C++ you can just get the probable cause by inspecting GetLastError() or the function itself can return helpful diagnostic (error) codes.
    If you manage to start the VM correctly from within Visual C++ please let me know. My email address is [email protected]
    good luck
    Henko

  • Help with calling a java application from inside another one

    Hello!
    I am having this problem which is getting on my nerves and dont know how to solve..
    I want to call from my java application, another java application. So i use the exec command. Then i want to read the output of this execution from my own application, (the "parent" process).
    But it doesn work properly. Something seems to happen and i dont get the whole output.
    The java program i want to call is created for running an application created with Matlab java builder.
    This program works when called from cmd, but seems not to work when called from inside a java application.
    The code of my java application is:
    Runtime rt = Runtime.getRuntime();
    Process child;
    // The java class getmagic is a special kind of java file that uses classes that work in matlab. It uses a component (.jar) file that is created from matlab java builder. thats why it wants the -classpath and the rest options.
    //I hope you wont get messed up in here.
    String[] callAndArgs = {"java","-classpath",".;C:\\Program Files\\MATLAB\\R2006b\\toolbox\\javabuilder\\jar\\javabuilder.jar;..\\MagicDemoComp\\magicsquare\\distrib\\magicsquare.jar -Djava.library.path=C:\\Program Files\\MATLAB\\R2006b\\bin\\win32;","getmagic","4"};
    try{
    child = rt.exec(callAndArgs);
    InputStream is = child.getInputStream();
    InputStreamReader isr = new InputStreamReader(is);
    BufferedReader br = new BufferedReader(isr);
    String line;
    while ((line = br.readLine()) != null)
    System.out.println(line);
    is.close();
    System.out.println(child.waitFor());
    System.out.println("Finished");
    }catch(IOException e) {
    System.err.println("IOException starting process!");
    }catch(InterruptedException e) {
    System.err.println("InterruptedException starting process!");
    The java program (getmagic) thats uses matlab gives the following output (after some time) when called in cmd with argument 4
    Magic square of order 4
    16 2 3 13
    5 11 10 8
    9 7 6 12
    4 14 15 1
    My program shown above only prints:
    Magic square of order 4
    1
    Finished.
    Do i do something wrong? How can i get the rest of the output???
    Thank you very much in advance,
    Stacey
    PS: I am sorry for the length of my post.

    Hello CaptainMorgan08, thanx for the instant reply.
    I tried, but no, i cant.
    Because i cannot include this java aplication that uses matlab into my application, cause 1) it needs special arguments in the compiler and during execution so it can be run and 2) it uses classes that java doesnt have. only the java-like matlab code.
    For example it uses:
    import com.mathworks.toolbox.javabuilder.*;
    import magicsquare.*; //the component which is made from matlab java builder.
    So i cannot compile it with my application!
    If you know of a way, please let me know!
    I know i might be missing something.. something that is obvious to you.. but i ve been working days=nights hardly no sleep..so you can excuse me if i say something foolish..
    Message was edited by:
    Stacey_Gr

  • Call a Java Application from MicroFocus COBOL (in UNIX environment)

    Hello,
    Could you please let me know, how to call a Java application from a MicroFocus COBOL application. If anyone has any code samples, that would be of great help.
    Thanks in advance,
    Tijo.

    You generally can't cause a program to be executed on a different >server. Basic security, you know. Besides this idea of having the Java >application run on a different server wasn't mentioned in your original >post. That leads me to believe we don't have the whole story.So I think you need to step back and find out what are the requirements. For example: Does your program need to start this Java application running, or is it already running and your program needs to connect to it somehow?
    My program has to start a Java class file, meaning that the Micro Focus COBOL module will call the Java class file. Will it be running on the same machine as your program, or on some other machine?
    For both cases, I would like to know the answer.a) Running on the same machine as my program is running.
    b) Running on the different machine.
    And then there are the questions about whether your program needs to have a conversation with the Java application, or whether it just needs to start it and that's all.
    COBOL program has to call a Java class by passing some parameters and Java class in turn process it and return some value back.. Kind of Request and Response model.Plenty of questions to be asked. Go and find out what they are.
    Sorry ... if I am not clear on my questions. Anyhow, thank you very much for providing the information.

  • Calling Java application from servlet

    Hi !
    I'm trying to run a Java application from within a servlet with Tomcat 4. I'm using the Runtime.getRuntime ().exec () method. So the application is run in a different JVM as a subprocess of the servlet. I use ObjectInputStream and ObjectOutputStream and a serializable object to enable communication between the servlet and the application.
    I tested the application and the serializable object with another Java application that works as the caller and it works fine. However, replacing the caller application with the servlet I get a StreamCorruptedException. The structure of the caller application and the servlet is the same.
    My questions are:
    - Is there something I should configure in Tomcat to create a subprocess ?
    - What is the cause of the StreamCorruptedException ? How do I get it with the servlet and not with the application ?
    - Should I use an environment with the call to Runtime.getRuntime ().exec () ? How do I use it ?
    - Is the called application forced to run in my servlet's context ?
    - Is there a better way to do this ?
    Thanks to all

    Here's my code:
    1. The serializable object:
    // Object Obj
    import java.io.*;
    public class Obj implements Serializable
    public int n;
    public Obj ()
    n = 0;
    public Obj (int n)
    this.n = n;
    public String toString ()
    return getClass ().getName () + " -> (n = " + n + ")";
    2. The application Sub (subprogram)
    // Application Sub
    import java.io.*;
    public class Sub
    private static File f;
    private static FileWriter fw;
    public static void main (String [] args)
    throws IOException, InterruptedException, ClassNotFoundException
    ObjectInputStream ois;
    ObjectOutputStream oos;
    Obj obj;
    ois = new ObjectInputStream (System.in);
    obj = (Obj) ois.readObject ();
    f = new File ("Sub.txt");
    fw = new FileWriter (f);
    fw.write (obj.toString ());
    fw.close ();
    oos = new ObjectOutputStream (System.out);
    oos.writeObject (obj);
    ois.close ();
    oos.close ();
    3. The application AMain (caller application)
    // Application AMain
    import java.io.*;
    class AMain
    private static File f;
    private static FileWriter fw;
    public static void main (String [] args)
    throws IOException, ClassNotFoundException
    Runtime r;
    Process p;
    ObjectInputStream ois;
    ObjectOutputStream oos;
    Obj obj, obj2;
    r = Runtime.getRuntime ();
    p = r.exec ("java Sub");
    oos = new ObjectOutputStream (p.getOutputStream ());
    obj = new Obj (5);
    oos.writeObject (obj);
    oos.flush ();
    B.comunica (obj);
    System.out.println ("AMain sends to Sub: " + obj.toString ());
    try
    p.waitFor ();
    catch (InterruptedException e)
    System.out.println ("Subprogram was interrupted");
    System.out.println (e.toString ());
    ois = new ObjectInputStream (p.getInputStream ());
    System.out.print ("Sub sends to AMain: ");
    obj2 = (Obj) ois.readObject ();
    System.out.println (" " + obj2.toString ());
    oos.close ();
    ois.close ();
    p.destroy ();
    4. The servlet SMain (the calling servlet)
    // Servlet SMain
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.sql.*;
    import java.io.*;
    import java.util.*;
    public class SMain extends HttpServlet
    public void doPost (HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException
    Runtime r;
    Process p;
    ObjectInputStream ois;
    ObjectOutputStream oos;
    Obj obj, obj2;
    int state, i;
    res.setContentType ("text/html");
    ServletOutputStream out = res.getOutputStream ();
    out.println ("<html>");
    out.println ("<head><title>Sub</title></head>");
    out.println ("<body>");
    out.println ("Invoking subprogram...");
    out.println ("<br>");
    try
    r = Runtime.getRuntime();
    p = r.exec ("java -cp .;c:\\Programs\\Apache~1.0\\webapps\\SMain\\WEB-INF\\classes Sub");
    out.println ("...invoked<br>");
    oos = new ObjectOutputStream (p.getOutputStream ());
    obj = new Obj (5);
    oos.writeObject (obj);
    oos.flush ();
    out.println ("<br>SMain sends to Sub: " + obj.toString () + "<br>");
    try
    p.waitFor ();
    catch (InterruptedException e)
    out.println ("<br>Subprogram was interrupted<br>");
    out.println ("<br>" + e.toString () + "<br>");
    state = p.exitValue ();
    out.println ("<br>Subprogram state: " + state + "<br>");
    ois = new ObjectInputStream (p.getInputStream ());
    out.print ("<br>Sub sends to SMain: ");
    obj2 = (Obj) ois.readObject ();
    p.destroy ();
    catch (SecurityException e)
    out.println ("<br>SecurityException<br>");
    out.println ("<br>" + e.toString () + "<br>");
    catch (IOException e)
    out.println ("<br>IOException<br>");
    out.println ("<br>" + e.toString () + "<br>");
    catch (Exception e)
    out.println ("<br>Exception<br>");
    out.println ("<br>" + e.toString () + "<br>");
    out.println ("</body>");
    out.println ("</html>");
    So, as you can see, both application AMain and servlet SMain invoke application Sub and pass it the serializable object Obj. Oddly enough, application AMain works fine whereas servlet SMain throws a StreamCorruptedException exception.
    johnpoole said:
    �It's hard to guess what would cause the exception without seeing code, but the interaction between the processes would differ from that between two applications, because the servlet process is started with a different class loader. I'm not sure which one the jvm started by the call would use.�
    How can I enforce that a System classloader be used in the call to Runtime.getRuntime ().exec () ? (I mean by System classloader a classloader equals to the one applications are launched from console).
    johnpoole said
    �Is there a reason why you aren't starting the second process manually and then connecting to it on a port?�
    The idea is providing a Web interface for an application running in the server. The servlet is used to restrict access to this application but once access is granted (passing the servlet) the application should not be constrained.

  • How to call a VB application from Java

    Hi,
    does anybody know how to call a VB application from java.
    Would appreciate if you can provide me with an example.
    thanks

    try exec()ing the cad program with the name of the file as a command line parameter...
    Runtime.getRuntime().exec("CADProg.exe Test.prt");
    i have no clue if this will work but it seems like it's worth a try.

  • Starting exetutable java file from java code

    Hi I was wondering how I can start a executable java file from java code?
    thanks

    Hi Mkaveli,
    Yes, it's possible. If you have a JAR executable, you've just to call the main method of its starter class. For a simple executable class, just call its main method.
    This way :
    SomeStarter.main(null); // if there's no argumentSmall precision : the executable JAR or class must be specified in the classpath of your application.

  • Connecting to desktop Java application from R/3

    I want to connect to a java application program in my desktop and return a parameter to R/3. I have installed Java connector and I want to call the java application from R/3 using Java connector.
    I was able to get few samples to setup the RFC destination for a remote server program, but I was not able to find anything for an application in the client system. How to setup the RFC destination for a Java connector to call the application in the desktop? Can anyone please answer this question.

    Hi Allam,
    1. Why do you need to connect from backend system to your desktop client? Did I understood it correctly that it's exacly what you want to do?
    2. I guess examples you saw are for JCO or JCA which is a part of SAP J2EE server. Simply speaking the server is waiting for a client request and your desktop application probably not. If you still are sure that server->desktop connection is what you need then you have to emulate the server on your self and then depending on what you need JCO/JCA you have to create a kind of container that will implement listening service.
    I'd like to hear your answer for question one to give you more detailed answer.

  • Can we call simple a java application from any one of this AS adapters

    Can we call a simple java application from any one of this AS adapters?
    Prakash
    Message was edited by:
    user629857

    You can achieve this using LiveCycle PDF Generator JAVA API. You can find required code here:
    Adobe LiveCycle * Quick Start (SOAP mode): Converting a Microsoft Word document to a PDF document using the Java API
    In parameters:
    //Set createPDF2 parameter values
    String adobePDFSettings = "Standard";
    String securitySettings = "No Security";
    String fileTypeSettings = "Standard OCR";
    "Standard OCR" file type setting will run OCR on input pdf. In the code, instead of doc file provide a pdf file. Resultant pdf will be searchable PDF i.e OCRed PDF.
    Feel feel to ask any further questions.

  • Calling Java Application from another

    How can i call a Java Application from another java App.
    eg., If my Java application is called MyApp and i would like call another java application from within it.
    One way could be by using "System". I would like to know if there is any other method and is portable.
    Thanks in advance.

    hi,
    it works and not!
    if you start an other class with a command like this the 2nd prog/class terminates too if you terminate the caller-class!
    dear
    oliver scorp

  • Calling a java application from j2ee web application

    Hi,
    I have a j2ee application in which i am making a call to a jar file which is a java application.
    Runtime a4 = Runtime.getRuntime();
    Runtime a = Runtime.getRuntime();
    String cmd[] = new String[14];
    cmd[0] = "cmd";
    cmd[1] = "/c";
    cmd[2] = "start";
    cmd[3] = "javaw";
    cmd[4] = "-jar";
    cmd[5] = CATALINA_HOME+"\\webapps\\AveksaTesting\\AveksaTestingJava\\dist\\AveksaTestingJava.jar";
    cmd[6] = SERVER_TESTS;
    cmd[7] = COLLECTOR_TESTS;
    cmd[8] = SYSTEM_TESTS;
    cmd[9] = CREATE_ORACLE;
    cmd[10] = DB_NAME;
    cmd[11] = DB_DUMP;
    cmd[12] = email;
    cmd[13] = isMIGRATE;
    try{
    java.lang.Process p = a.exec(cmd);
    Now in the called java application, i am first shutting down the tomcat server by calling shutdown.bat script and then starting it using startup.bat. But the problem i am facing is when i restart the server from java application, it says address already in use(i.e. port 8445 on which tomcat is runninng).
    Id i just call the java application and do the same operation it works fine. I guess when i am calling java from j2ee application, j2ee still has some threads holding java and not shutting down tomcat properly.
    Can anyone suggest me what can be done in this case. I have to call a java application from j2ee and restart the tomcat server many times.
    Thanks in advance
    -Vikram

    Annoyingly crossposted.
    http://forum.java.sun.com/thread.jspa?threadID=730657

  • How to invoke java application from ABAP

    How to invoke java application from ABAP  ? Suppose I needto execute a EJB wihic is running on my SAP J2EE Enigne from an ABAP Program .
    Thanks,
    Manish

    Hi Manish,
    did you get some further documents concerning "abap program calls ejb"?
    If yes, could you please send me some informations.
    Thank you for your help.
    Kind regards, Patrick.

Maybe you are looking for