old_soul_on_the_run
old_soul_on_the_run

Reputation: 289

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);
}}

Upvotes: 1

Views: 297

Answers (3)

Julian Fondren
Julian Fondren

Reputation: 5619

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 ..

Upvotes: 1

Sumit Singh
Sumit Singh

Reputation: 15886

Simply if you want to use any class in java then that class must be present in class-path because when you run your program then all class needed for that is always looking in class path..
So you have to set class-path of your demo.jar
There is no of ways to set class path take a look of this How set class path

or simply you can do another option use java parameter -cp

java -cp /your jar path/demo.jar test

Upvotes: 0

casablanca
casablanca

Reputation: 70701

Have a look at this: Packaging Programs in JAR Files

Once you have both your main class and JAR file ready, you can simply run the main class with the JAR file on the classpath and Java will find it. Assuming the demo class is in demo.jar and your main class is test (as in your example):

java -cp demo.jar test

Upvotes: 3

Related Questions