John Tate
John Tate

Reputation: 772

Java class compiles but cannot be loaded

I have compiled a class and the file shows up but I can not run it with java or use it from other classes, where either java or javac act as if it isn't there.

It compiles...

john@fekete:~/devel/java/mysqlexample$ javac first/mysql/MySQLAccess.java 
Note: first/mysql/MySQLAccess.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.

It doesn't seem to exist to java...

john@fekete:~/devel/java/mysqlexample$ java first/mysql/MySQLAccess.class
Error: Could not find or load main class first.mysql.MySQLAccess.class
john@fekete:~/devel/java/mysqlexample$ java first/mysql/MySQLAccess
Error: Could not find or load main class first.mysql.MySQLAccess

I can't use it from other classes.

first/mysql/test/Main.java:3: error: cannot find symbol
import first.mysql.MySQLAccess;
                   ^
  symbol:   class MySQLAccess
  location: package first.mysql

The files are structured as such and I compile from the root of that structure.

john@fekete:~/devel/java/mysqlexample$ ls -l first/mysql/
total 12
-rwxr-xr-x 1 john john 3625 May  2 07:59 MySQLAccess.class
-rw-r--r-- 1 john john 3052 May  2 07:59 MySQLAccess.java
drwxr-xr-x 2 john john 4096 May  2 08:02 test
john@fekete:~/devel/java/mysqlexample$ ls -l first/mysql/test/
total 4
-rw-r--r-- 1 john john 205 May  2 08:02 Main.java

Importing first.mysql.* does not work.

Perhaps I need to change my classpath.

john@fekete:~/devel/java/mysqlexample$ echo $CLASSPATH 
/usr/local/mysql-connector-java/mysql-connector-java-5.1.24-bin.jar

Upvotes: 0

Views: 536

Answers (2)

Edwin Buck
Edwin Buck

Reputation: 70909

the java command invokes the JVM, which doesn't run source code. So

java first/mysql/MySQLAccess.java

won't work as it is written. Instead you need to call the resource name, which would be

java first.mysql.MySQLAccess

except that the above command line is likely to not work because you probably haven't configured your JVM to search the current directory for class hierarchy trees. You probably want something like

java -classpath . first.mysql.MySQLAccess

to load in the class at first/mysql/MySQLAccess.class; but, that's not the whole story. The CLASSPATH environmental variable also comes into play, which is how it will load the mysql-connector-java-5.1.24-bin.jar. However, if you run into problems, I suggest that you make its inclusion explicit, like so

java -classpath .:/usr/local/mysql-connector-java/mysql-connector-java-5.1.24-bin.jar first.mysql.MySQLAccess

Upvotes: 4

mata
mata

Reputation: 69012

Remove the .java when trying to run java classes.

Also, make sure your class has a main method, and that it is in the package first.mysql, that can be a reason why other classes can't see it.

Upvotes: 1

Related Questions