1

You can use this command to start a jar file and specify a main class.

java -cp file.jar path.to.MainClass

My problem is that I just have a class that is not contained in a package. So the main class is just called MainClass. So the command becomes

java -cp file.jar MainClass

The problem is that java does not seem to be able to load the class and just says it could not be found or loaded.
Is there a way to start a jar with the -cp argument like that?

omajid
  • 14,165
  • 4
  • 47
  • 64
user11227590
  • 51
  • 1
  • 6
  • 1
    In general, the syntax you posted is supported and should work. Please give us more information. What does the current directory tree look like? Does `file.jar` exist? What is the only exact error that you see? – omajid Jun 17 '20 at 20:07
  • @omajid It says "Fehler: Hauptklasse MainKt konnte nicht gefunden oder geladen werden" (german), which translates to "Error: Main class MainKt could not be found or loaded". The manifest contains the line "Main-Class: MainKt". Everything works if I start it with "java -jar file.jar". – user11227590 Jun 17 '20 at 20:46
  • Okay. Is the class in the main jar? I understand it's in the current directory? Try `java -cp file.jar:. MainClass`. That is, a classpath that includes both the `file.jar` file and the current director (`.`) separated with a colon (`:`) on Linux. On Windows, use a semicolon (`;`) as the separator instead. – omajid Jun 17 '20 at 20:53
  • @omajid it's all in the jar itself. I tried your commands but that didn't change anything. – user11227590 Jun 17 '20 at 21:29
  • 2
    @user11227590 There is no problem in running `java -cp file.jar MainClass`, assuming the `file.jar` file exists and it contains a `MainClass.class` file in it on the root level of the jar. Please [edit] your question to include the source code of the `MainClass` file and the content of the `.jar` file with `jar -tf file.jar`. Also show how you have compiled the java source code and have built the jar file. – Progman Jun 17 '20 at 21:58
  • 1
    @omajid OOOOOOPS I really accidentally made a capitalization mistake while doing this. I feel so stupid right now... The file was called MainClass and the class was just Mainclass without the capital C. I got it confused. Sorry for wasting your time. – user11227590 Jun 17 '20 at 22:39

1 Answers1

1

Just run:

java -cp file.jar MainKt

Main-Class in manifest only impacts java -cp file.jar, not when used with a class argument like MainClass (which presumably doesn't exist) or MainKt.

Also, if your class is really named MainClass inside the MainKt.java source file, it should be renamed to match the source file name (or vice versa) first; see e.g. this question.

Will
  • 6,601
  • 3
  • 31
  • 42