Arvind
Arvind

Reputation: 6474

Can i somehow run previously compiled java bytecode from a new Java program?

Is it possible to first compile a set of Java source code files into bytecode, and later run that bytecode-- not directly, but by adding commands to another java program-- such that this new java program (in its various classes/functions) runs the previously compiled java bytecode?

If this is possible, then what is/are the required command(s) to do this?

Upvotes: 0

Views: 458

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500625

Absolutely - and that's what libraries are all about! They're typically distributed as jar files, but you don't have to use jar files in order to reuse the code.

All you need to do is make sure that it's on the classpath at both compile-time and execution time.

For example, create the following files:

lib\p1\Hello.java:

package p1;

public class Hello {
    public static void sayHi(String name) {
        System.out.println("Hi " + name + "!");
    }
}

app\p2\Greeter.java:

package p2;

import p1.Hello;

public class Greeter {
    public static void main(String[] args) {
        Hello.sayHi(args[0]);
    }
}

Now let's compile our "library":

$ cd lib
$ javac -d . p1/Hello.java
$ cd ..

And now, by adding that to the classpath, we can use it in our "app":

$ javac -d . -cp ../lib p2/Greeter.java
$ java -cp .:../lib p2.Greeter Jon
Hi Jon!

(This all works on Windows with the one change of using ";" instead of ":" in the joint classpath on the last line.)

Upvotes: 5

Related Questions