I am an experienced programmer, but haven't used Java in years - mostly C# - and used an IDE in the past. I'm trying to compile some code from the command line on my Mac, but can't get my test file to find my source code. I'm assuming the problem lies somewhere in the space of packages, file structure, classpaths, and import statements - but I've put a couple hours in (including hunting on Stack Overflow) and am still stuck.
Here's what I have:
Directory structure:
ProjectName
|
--src
|
--SourceClass
--test
|
--SourceClassTest
--external
|
--testng-6.8.7.jar
My SourceClass looks like this:
package ProjectName;
public class SourceClass<T>{
}
Very simple. Obviously, there will be more - but I wanted to start with making sure I had all this setup stuff correct before I actually did coding.
My test class looks like this:
package ProjectName;
import java.util.*;
import org.testng.Assert;
import org.testng.annotations.*;
public class SourceClassTest{
#Test
private void createEmptySourceClass(){
SourceClass<Object> sourceClass = new SourceClass<Object>();
Assert.assertTrue(sourceClass.isEmtpy());
}
}
The sourceClass compiles with no issue with "javac src/*.java", run from the "ProjectName" directory. I want to see this fail with an error along the lines of "SourceClass doesn't have an isEmpty() method", but instead I run javac like this from the "ProjectName" directory:
javac test/*.java -classpath external/testng-6.8.7.jar
and get this exception:
test/SourceClassTest.java:12: error: cannot find symbol
SourceClass<Object> tree = new SourceClass<Object>();
^
symbol: class SourceClass
location: class SourceClassTest
test/SourceClassTest.java:12: error: cannot find symbol
SourceClass<Object> sourceClass = new SourceClass<Object>();
^
symbol: class SourceClass
location: class SourceClassTest
2 errors
I've tried a lot of things -adding an import statement, adding a sourcepath to the javac command, compiing the sourceClass as a jar and putting it in the bin directory then adding that to the classpath, but I can't get the test to find the SourceClass symbols.
Any idea what I am missing here?
It works if you compile into a separate target directory. E.g,
mkdir target
javac -d target/ src/*.java
javac -classpath target/ test/*.java
When you do javac src/*.java, it will create the .class file in the src directory itself. By default, any classes you reference are assumed to be in the same package. So even if you add src/ to the classpath, it looks for src/ProjectName/SourceClass.class, which it does not find. When you pass the -d target/ option, it creates the proper package hierarchy, so and finds the class.
Relevant documentation from the javac official doc:
You should arrange source files in a directory tree that reflects
their package tree. For example, if you keep all your source files in
C:\workspace, the source code for com.mysoft.mypack.MyClass should be
in C:\workspace\com\mysoft\mypack\MyClass.java.
By default, the compiler puts each class file in the same directory as
its source file. You can specify a separate destination directory with
-d (see Options, below).
...
...
-d directory Set the destination directory for class files. The directory must already exist; javac will not create it. If a class is
part of a package, javac puts the class file in a subdirectory
reflecting the package name, creating directories as needed. For
example, if you specify -d C:\myclasses and the class is called
com.mypackage.MyClass, then the class file is called
C:\myclasses\com\mypackage\MyClass.class. If -d is not specified,
javac puts each class files in the same directory as the source file
from which it was generated.
Note: The directory specified by -d is not automatically added to your
user class path.
My guess is it can't find SourceClass because the file defining that class is under src, and you didn't mention that directory in your javac command line.
If I were you, I would change the file hierarchy to this:
ProjectName/src/ProjectName/SourceClass.java
ProjectName/src/ProjectName/SourceClassTest.java
ProjectName/external/testng-6.8.7.jar
Then run javac src/ProjectName/*.java -classpath external/testng-6.8.7.jar.
Or keep the file hierarchy the way it is, and run javac src/*.java test/*.java -classpath external/testng-6.8.7.jar
The accepted answer is correct, but it misses one critical point: when javac is asked to compile *.java (as opposed to foo.java, and then foo2.java ...) it treats them as a single package and accepts references between them.
That's the magic. Other languages do this less implicitly with header files.
Even after reading this post, it took me some time to figure that out, against my inherent assumption that a program running singly on files one after the other would (should) produce the same result as running that program on a group of files. My bad; the * is NOT a mere convenience, but critical.
Related
Consider the following code:
package com.a.b;
class Test {
public static void main(String[] args) {
System.out.println("Hello to the world of packages");
}
}
I've compiled the program like so:
javac Test.java
This created Test.class file in the current working directory. How should I run the program now? I tried:
java Test
but I'm getting a "No class def found error". If I compile this way:
javac -d . Test.java
It's creating directory structure, then I'm able to run through
java com.a.b.Test
If I can compile without directory hierarchy, why can't I execute?
In your first command:
javac Test.java
It compiles fine because there are no errors and places the Test.class file in the current directory, because that's where Test.java resides, as per the documentation:
If the -d option is not specified, then javac puts each class file in the same directory as the source file from which it was generated.
The source file is in the current directory so the class file is placed in the current directory. Now when you execute like so:
java Test
There's an error because you must use the fully qualified class name. You specified a package, and even though it's in the current directory, you still must use the fully qualified name to specify where it is. Without the full name, Java can't find it an execute it, thus the error. You can do the following:
java com.a.b.Test
Java will find it appropriately and all will execute fine.
Now, I would recommend using the -d option to correctly place your class files for organization. I would also recommend actually creating the packages you specify, so put your Test.java file in the directory ./com/a/b.
You must always run your Java program with the fully qualified class name:
It doesn't matter whether you compile it using the javac -d option.
So, in your case, it will be:
java com.a.b.Test
It is a best practice to compile it with the -d option and store .class files in the proper directory structure as per the package name.
Update
Also, ensure your current directory is in the class-path.
Try running this:
java -cp . com.a.b.Test
Update 2
When the -d option is not used with javac, the class files are created in the current directory. You will have to move/copy the class file(s) manually to the appropriate directory and then execute them. The -d option is a short cut of achieving this.
Java search for classes in classpath. By default classpath contains only currrent directory.
When Java search for class it iterates thru classpath element. If element is directory it search file with name of the class end extension .class in some subdirectory. To be precise this subderectory is found by replasing dots to directory separation simbol (/ or \ depending on your operation system) and resolving result.
1) Add your class to the java build-path
2) Run it with the full path.
Java and Gradle beginner's question.
I made a project directory for java and gradle test:
The directory hierarchy :
HelloWorld.java:
package foo.bar;
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, world");
}
}
build.gradle:
apply plugin:'java'
Then,gradle build this project and generated what i need.
As you see above, my problem is why doesn't this execute correctly? Even through I cd to .class path.
======================================================================
While, if I remove package foo.bar; in HelloWorld.java, and repeat gradle commands and execute at he.bak directory then the error remained the same.
But when I cd to the directory where HelloWorld.java placed. everything goes OK!Why? something related with CLASSPATH environment variables or other causes?
////////////////////////////////////////////////////////////////////
UPDATE
////////////////////////////////////////////////////////////////////
Thought you guys' warm replies, I know that I should combine the CLASSPATH and the period-separated executable .class file to figure out what's going on when executing java class file.
I experiment my thought resulting in 2 point to this question:
The -cp option path parameter A/B plus the executable file c.d.e.class finally form the A/B/c.d.e.class full path where the class is actually located.
If I specify the package in source code file with package d,I must split the full path in the form of java -cp A/B/c/d e.class. split in other ways all will result in errors.
something I am not sure here is :
When I specify my package path in my source code file, It determined the only classpath when executing corresponding executable, right?
If it is the truth, How does a project with lots of package and sources files work?
What's the root principle?
When in build/classes/main try java foo.bar.HelloWorld instead of java HelloWorld
The reason you need to specify foo.bar.HelloWorld is because you specified package foo.bar;. This tells java that the class should be in foo/bar/HelloWorld and the fully qualified name for HelloWorld is foo.bar.HelloWorld. If you want to execute the class from a different working directory however, you can specify the classpath explicitly using the -cp option, e.g., java -cp c:\myproject\build\classes\main foo.bar.HelloWorld.
By the way, the classpath default is the current working directory (i.e., .) but java -cp c:\myproject\build\classes\main foo.bar.HelloWorld will NOT have the classpath set to the current working directory if it is explicitly set using the -cp option. If you want to include the current working directory but explicitly set it, or even add more directories, you can chain them using semicolons like this: java -cp .;c:\myproject\build\classes\main foo.bar.HelloWorld. So this will include both the current working directory and the directory I specified.
I am not very clear with the following question from SCJP Book (I read the solution and explanation though) ..
Consider the following directory structure :-
foo --> test --> xcom --> A.class, B.java
Here foo, test and xcom are directories. A.class and B.java are the files in xcom directory.
Following are the source codes of corresponding files:-
A.java
package xcom;
public class A { }
B.java
package xcom;
public class B extends A { }
The default classpath is /foo.
Now, in order to compile B.java, I keep my current directory as test and give :-
javac -classpath xcom xcom/B.java
Here I give the classpath as xcom which has A.class. But still it does not find class A. Why is it so??
If your classes are in package xcom, then your classpath needs to be at the directory directly above that. In this case, the classpath should be foo/test.
And if your current directory is foo/test, then this should be your javac:
javac -classpath . xcom/B.java
Because you have to specify classpath root to -classpath argument, like javac -classpath . xcom/B.java. To compile class B java compiler requires class A, it tries to locate class A file in {classpathroot}/xcom/.
Note: . - is a current directory
I think the root cause here is a misunderstanding of a "fully-qualified name" in Java.
The fully-qualified names of your two classes are xcom.A and xcom.B. Their source is in files A.java and B.java in a directory named xcom; the fully-qualified names dictate the directory structure. When you are going to use the files, either to compile them or run them, the classpath contains one or more locations from which the fully-qualified names can be found; so java is looking for xcom\A.java and xcom\B.java (when compiling) and xcom\A.class and xcom\B.class (when running).
That is why the classpath needs to specify the directory that contains xcom.
As you progress to more complex environments: the classpath can be a list of such locations; each location is separated by a semicolon on windows and a colon on unix systems. Each location can be a directory, as you've already seen, but it can also be a jar file. jar files are in zip file format, and zip files have a directory structure just like disks do. So you could zip up your class files, maintaining their xcom parent (but not their full paths), and specify the jar file in the classpath instead of a directory.
I know the question was already answered somewhat, but thought you might like the background explanation as well.
I'm new to working with Java from the command line and I don't get it. I read previous CLASSPATH questions but still didn't get my problem to work.
I have the following class in C:\Temp\a\b\c
package a.b.c;
public class Hello
{
public static void main(String args[])
{
System.out.println("Hello World!");
}
}
The package name is intentional.
I compiled it fine and I put the Hello.class file inside C:\Temp\a\target
Now in the command line I go to C:\Temp\ and execute the following:
java -cp .\a\target a.b.c.Hello
It complains that it cannot find the class a.b.c.Hello
Thanks in advance!!
and I put the Hello.class file inside C:\Temp\a\target
This is wrong. It should be placed in the same folder as the .java file. The source code itself is declared to be in the package a.b.c; so, the .class file should really be kept in \a\b\c folder.
Then, to execute it just do:
C:\Temp>java -cp . a.b.c.Hello
Avoid "putting" the classfiles anywhere. The following should work:
javac -d c:\temp c:\temp\a\b\c\Hello.java
# creates Hello.class in c:\temp\a\b\c
java -cp c:\temp a.b.c.Hello
To expand on BalusC's point: the classpath defines a "root". When java is looking for your classes, it will start at each root (or jar) in your class path and drill down through the directories to match the package strucutre. You still need to have you class in a directory structure that matches its package name. In your case, to execute
java -cp .\a\target a.b.c.Hello
you would move the file to
.\a\target\a\b\c\Hello.class
Years ago, I too found this baffling.
Java will try to search for a directory structure a\b\c from starting in target and as you notice, it wont work.
Move the whole directory into target and you'll be fine, it should look like:
C:\Temp\a\target\a\b\c\Hello.class
You may compile it with the -d option which tall the compiler where to put the class file.
Many project structures are like this.
C:\whatever\projectname\src
C:\whatever\projectname\classes
C:\whatever\projectname\bin
C:\whatever\projectname\lib
C:\whatever\projectname\doc
That way you can always step on your project directory and type:
javac -d classes src\*.java
Which will compile all the sources in the src directory and will place them in the classes directory.
Then execute your program:
java -cp classes a.b.c.Hello
You may optionally place required jars in lib
This works pretty fine for small programs ( < 10 src files and 2 - 3 jar libraries ) If it grows beyond that, you could probably use an IDE or ant
The good thing about following this project structure is that some IDES ( as IntellJ idea ) just pick them very easily when you create a new project. You select "Create project from existing sources" and then you can continue from there.
I like compiling and editing at the command line a lot!!
My Java classes organization has gotten a little messy so I'm going over something I've skipped in my Java learning: the classpath. I can't quiet get beloved classes to compile in the packages I have created for them. Here's my folder hierarchy:
.
com/
david/
Greet.java
greeter/
SayHello.java
SayGoodbye.java
Where SayHello's constructor just prints "hello" and SayGoodbye's prints "Goodbye" and Greet's main method just creates those two objects. At the top of SayHello is package com.david.greeter; and likewise with SayGoodbye and Greet's is package com.david;
In the greeter folder I was able to compile both java files but if I go to the current directory (the directory that holds com) and do javac -cp "com.david.greeter.*" com/david/Greet.java it says it can't find the classes as well as saying package com.david.greeter doesn't exist. I've also tried setting the $CLASSPATH manually.
I'm at my wit's end here, Stackoverflow (as I normally am when I post here). Do any of you know what I am doing wrong?
The java compiler will traverse the sub-directories of the classpath looking for the packages it needs.
So, your command line should be as follows:
javac -cp "." com/david/Greet.java
When the compiler sees a reference to com.david.greeter.SayHello while compiling Greet.java it will start with the directory in the classpath and traverse the hierarchy looking for the package it needs.
First, as documented in Setting the Classpath, the way you're currently setting your class path is wrong. Class path entries should be filename or directory. So using com.david.greeter.* doesn't make any sense. Second, the current directory is in the class path by default:
The default class path is the current directory. Setting the CLASSPATH variable or using the -classpath command-line option overrides that default, so if you want to include the current directory in the search path, you must include "." in the new settings.
So if you execute javac (here is the man page by the way) from the folder containing com, you don't have to tweak anything, just type:
javac com/david/Greet.java
And javac will go through the directory tree to find references (e.g. SayHello if you're using it from Greet) and compile them too.
And by the way, if you have to set the class path, don't use the $CLASSPATH environment variable, this is just a bad practice in most case, prefer the -cp option.
If you are in the folder containing com, then try this:
javac -cp . com\david\Greet.java
This is incorrect (as the compiler has already told you):
javac -cp "com.david.greeter.*
Open a command shell and navigate to the directory that contains the "com" directory.
I think you really want this to compile SayHello.java and SayGoodbye.java:
javac -cp . com/david/greeter/*.java
This to compile Greet.java:
javac -cp . com/david/*.java
And this to run:
java -cp . com.david.Greet
The "com" directory should not be current, it should be a child directory to current. You need step one level upper and launch again. No extra care about classpath should be needed at this point.