I have a content of compiled Java class as a binary file (named X.class
). Let's assume it has some class inside with a proper main
method, but I don't know original class name (and it's not X
).
How can I run it with java
using single command line?
You can get the name of the class using javap -c <filename>
. From that point on, it's just shell games. This works on OS X:
java $(javap -c File.class | head -n 2 | tail -n1 | cut -f3 -d\ )
Note the space after the \
in the subshell - this is requires to isolate the class name.
Update based on @nikolay-vyahhi feedback:
If you're not sure at which position the class name will appear (e.g. when it's unknown whether the class is public or not), you can use tr
and grep
, like so:
java $(javap -c File.class | head -n2| tail -n1 | tr [:space:] \\n | grep -A1 "class\|interface" | tail -n1)