Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run Java .class file from another .class file? (java newb)

I've been running different individual Java .java files in the Netbeans IDE by right-clicking the .java files themselves in the Project Explorer of Netbeans (the portion normally at the upper left part of Netbeans).

However, i've been googling on how to make a class file run another class file using code, but to no avail.

I have a project named "loadanotherfile" with 2 files, namely: Loadanotherfile.java and otherfile.java

I'm trying to make Loadanotherfile.java run otherfile.java, but I'm not exactly sure how. I read about Classloaders and URLClassloaders however these methods don't seem suitable for my purpose of running another .java file.

Below is the code of the 2 files i mentioned.

Loadanotherfile.java

package loadanotherfile;

public class Loadanotherfile {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        System.out.println("Hello World!");
        // TODO code application logic here
    }
}

otherfile.java

package loadanotherfile;

public class otherfile {

    public static void main(String args[])
    {
        System.out.println("This is the other file.");
    }
}

I have a feeling that the task has something to do with using the "import" syntax (namely something like import loadanotherfile.* but even if my guess is correct, I'm still not sure on how to make my Loadanotherfile.java run otherfile.java using code.

How can I load otherfile.java using Loadanothefile.java?

Cheers

like image 571
Last Man Standing Avatar asked Nov 01 '12 09:11

Last Man Standing


3 Answers

In Loadanotherfile.java

otherfile.main(args);
like image 131
Matt Clark Avatar answered Oct 16 '22 11:10

Matt Clark


Compile the two together, and then from Loadanotherfile,

otherfile.main(args);

will do the trick. You don't need to import since you're in the same package. Note the linked tutorial.

I would investigate (however) class instantiation, and creating an instance of a new class to invoke upon. Invoking static methods from static methods isn't very OO.

like image 29
Brian Agnew Avatar answered Oct 16 '22 12:10

Brian Agnew


Try This:

className.main(Args){
}

This works! ive tested it myself.

like image 31
user3343456 Avatar answered Oct 16 '22 11:10

user3343456