Works in sbt but not raw Java: after using `javac` to compile a .class file, why can't `java` find it?

StackOverflow https://stackoverflow.com/questions/15781374

  •  31-03-2022
  •  | 
  •  

Question

I used ObjectWeb's ASMifier to get a 'HelloDump.java', and added classloader and a main method to load and run a spoofed "HelloWorld".

If I run 'HelloDump.java' in the build tool sbt, everything works fine and outputs "HelloWorld!".

But if I use raw Java, it breaks. 'HelloDump.java' seems to compile OK, but the resulting 'HelloDump.class' is clearly present, yet doesn't seem to be recognized (check the sequence below):

$ julianpeeters@julianpeeters-virtual-machine ~/asm-example $ javac -cp lib/asm-all-4.1.jar HelloDump.java

$ julianpeeters@julianpeeters-virtual-machine ~/asm-example $ ls
DumpLoader.java.bak  HelloDump.class.bak                 Hello.java.bak
Hello.class.bak      HelloDump$DynamicClassLoader.class  lib
HelloDump.class      HelloDump.java                      README.md

$ julianpeeters@julianpeeters-virtual-machine ~/asm-example $ java -cp lib/asm/all/4.1.jar HelloDump
Exception in thread "main" java.lang.NoClassDefFoundError: HelloDump
Caused by: java.lang.ClassNotFoundException: HelloDump
    at java.net.URLClassLoader$1.run(URLClassLoader.java:217)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:205)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:321)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:294)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:266)
Could not find the main class: HelloDump. Program will exit.

Explicitly adding . to the classpath doesn't help either.

So why does this work in sbt, but not in raw Java, and how can I fix it?

Thanks, any advice is appreciated, -Julian

Was it helpful?

Solution

Add . to your CLASSPATH, so your command becomes: java -cp lib/asm-all-4.1.jar:. HelloDump

The reason the JVM cannot find the class is that it looks only on the classpath and nowhere else.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top