java: find program name, parse integer argument
A simple test case to demonstrate my 2 problems:
public class Numbers {
private static void usage() {
System.err.println("Usage: java " + getClass().getName() + " range");
System.exit(1);
}
public static void main(String[] args) throws IOException {
try {
int range = Integer.parseInt(args[0]);
} catch (Exception e) {
usage();
}
}
}
- Can't call
getClass()
from a static method - If no arguments have bee开发者_如何转开发n supplied at the command line, I'll get
ArrayIndexOutOfBoundsException
message instead of theusage()
output. Why doesn't catch (Exception e) catch it?
1) getClass is a method on the Object type. In static methods there is no object to call the getClass on
2) The exception is caught in your example - I just tested it.
Works for me, exception is caught.
Getting the class name from a static method without referencing the Numbers.class.getName()
is difficult.
But I found this
String className = Thread.currentThread().getStackTrace()[2].getClassName();
System.err.println("Usage: java " + className + " range");
How about this in your static method to get the class name: get the name of the class at the top of the current stack trace.
StackTraceElement[] stackTraceElements= new Exception().getStackTrace();
String className = stackTraceElements[0].getClassName();
Your first question can be answered by looking at this question: Getting the class name from a static method in Java.
You can't use getClass() method without an reference object.
Try this
System.err.println("Usage: java " + Numbers.class.getName() + " range");
It is not possible to use member variable/method without object reference from a static method.
int range = Integer.parseInt(args[0]);
Above will return ArrayIndexOutOfBoundException, not IOException.
So your code won't compile.
If you create a new instance of Numbers you can call getClass()
on that.
(new Numbers()).getClass().getName()
and as @Petar Ivanov has already said, the Exception is caught as expected.
To get the class you can do 1 of two things:
Class cl = null;
try
{
cl = Class.forName("Numbers");
}
catch(ClassNotFoundException ex)
{
}
or:
Numbers n = new Numbers();
Class cl = n.getClass();
The first is obviously better because you don't waste memory allocating. Though if you're just planning on returning right away, then this probably doesn't matter much in this case.
精彩评论