Home > Enterprise >  Compiling java class from command line defined in a package [duplicate]
Compiling java class from command line defined in a package [duplicate]

Time:09-27

I'm able to compile and run a simple hello world program from command line with

javac hello.java
java hello

however, if I had a package statement at the top package com.mypackage.myclass and try the same I get

Error: Could not find or load main class Reflection

What is exactly happening? And how do I fix it? Thanks.

UPDATE: Thanks everyone. I already had created the directory structure manually. In order for this to work I have to run java com.mypackage.myclass from the root directory, otherwise it will not work. Still don't understand the underlying mechanism. What is exactly happening?

CodePudding user response:

If you have a java class like com.example.test.Main then the compiled class should be in a folder com\example\test and the class file name Main.class

You could manually do it, but compiler has a switch -d <target folder> which will create the folder structure for you.

javac -d . Main.java

In the above command the target folder is the current folder where you have the Java source file.

Once compiled you must use fully qualified name of the class to execute from the same folder you compiled the java file.

java com.example.test.Main

Screen Cap

  •  Tags:  
  • java
  • Related