javajarmainclass

Executing java class in JAR from a java program


My Question is:

I have a test.java class which is the main class. There is one more class(non-main class) which is present in JAR file. Now i want to compile and execute demo class present in JAR from the main class present outside the JAR. Please explain why.

public class test
{   
public static void main(String args[])
{
    demo d1 = new demo();
    demo d2 = new demo("message passed from main class");
}
} 

public class demo
{
demo()}
System.out.println("message in demo class");
}
demo(String str)
{
System.out.println(str);
}}

Solution

  • I guess the proper answer us 'use ant', but:

    javac test.java
    javac demo.java
    jar cf test.jar test.class demo.class
    jar ufe test.jar test
    

    and then,

    java -jar test.jar
    

    If you intend to expand on this, and continue not to use ant, you'll likely want your build system to stop on an error, and will notice that 'javac' doesn't return non-zero on error. Pipe its stderr to a temporary file and then quit depending on grep's non-zero return of that file. e.g., from an on-device build script that cannot use ant:

    cd src
    for F in R.java Maze.java EmptyActivity.java; do
      javac -d ../build/classes $P/$F 2> ~/tmp/javac.out
      echo -en "\033[1m"; cat ~/tmp/javac.out; echo -en "\033[0m"
      grep error ~/tmp/javac.out && exit
    done
    cd ..