user4896245
user4896245

Reputation:

Error caused on runtime of java class file

How do I compile and run java files if you don't know the specific package used by the developer...

I got a folder of java files written by someone else, and I'm trying to compile and run the java files, I can compile the files by running javac *.java, but if I try to run the main class by calling java MainClass, I get an error like so: Error could not find or load main class MainClass, Caused by: java.lang.NoClassDefFoundError: SomePackageName/MainClass (wrong name: MainClass)

I have no idea whats the SomePackageName its defined by the developer and I have no control over that.

so the question is how do I compile and run the java files if all I know is which is the main class?

Upvotes: 0

Views: 243

Answers (1)

rzwitserloot
rzwitserloot

Reputation: 103893

  1. Fully qualified class names are of the form: com.foo.Bar, where com.foo is the package (e.g. the file defining the Bar class starts with the line package com.foo;), and Bar is the name (e.g. the file contains the line public class Bar {).
  2. When running java and specifying classpath+classname, you pass a class name. Not a file name. So to run this file you'd write java -cp /path/to/base com.foo.Bar.
  3. fully qualified names must match directory structure both at runtime (class files) and compile time (java files). So, here you should have say /Users/Foghunt/projects/myproj/src/com/foo/Bar.java and after compilation you should have e.g. /Users/Foghunt/projects/myproj/build/com/foo/Bar.class
  4. The 'base dir' is the one that contains the first package directory. So, the base dir for the source file is /Users/Foghunt/projects/myproj/src and for the compiled result is /Users/Foghunt/projects/myproj/build.
  5. The base dir needs to be in the classpath. Classpath entries are file paths. So, to run this thing you'd write java -cp /Users/Foghunt/projects/myproj/build com.foo.Bar.
  6. javac doesn't mind if you don't go through the trouble of properly defining things (e.g. running javac *.java in /Users/Foghunt/projects/myproj/src/com/foo does work), but it gets complicated quickly if you have multiple packages.
  7. In general you should be using build systems. If you've inherited this project, check for a file named build.xml or pom.xml or build.gradle in the root of the project. If it is there, use a web search engine (build.xml -> search for java ant, pom.xml -> java maven, build.gradle -> java gradle), and use that to build the project, don't run javac yourself.

There you go. Armed with that knowledge you can now analyse, build, and run any java project.

Upvotes: 2

Related Questions