Tuesday, January 19, 2016

accessing the command line in java

would be convenient to be able to define a main() in an abstract superclass and have it automatically "run" the subclass that java was invoked with. there's nothing builtin, but at least on linux this info is easy to get.  here's a simple demo

import java.nio.file.Files; import java.nio.file.Paths; public static void main(String[] args) throws Exception { // linux only, might work on windows // https://cygwin.com/ml/cygwin/2007-04/msg00817.html byte [] bytes = Files.readAllBytes(Paths.get("/proc/self/cmdline")); String [] text = new String(bytes).split("\0"); String klassname = text[text.length-1-args.length]; System.out.println(klassname); } if anyone tries this on windows, leave a comment if it works

No comments: