Reputation: 22988
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();
}
}
}
getClass()
from a static methodArrayIndexOutOfBoundsException
message instead of the usage()
output. Why doesn't catch (Exception e) catch it?Upvotes: 5
Views: 3573
Reputation: 8261
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.
Upvotes: 1
Reputation: 8534
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");
Upvotes: 3
Reputation: 1466
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.
Upvotes: 0
Reputation: 43823
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.
Upvotes: 0
Reputation: 88378
Your first question can be answered by looking at this question: Getting the class name from a static method in Java.
Upvotes: 1
Reputation: 43560
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();
Upvotes: 1
Reputation: 93030
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.
Upvotes: 6