5

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();
        }
    }
}
  1. Can't call getClass() from a static method
  2. If no arguments have been supplied at the command line, I'll get ArrayIndexOutOfBoundsException message instead of the usage() output. Why doesn't catch (Exception e) catch it?
Alexander Farber
  • 21,519
  • 75
  • 241
  • 416

7 Answers7

6

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.

Petar Ivanov
  • 91,536
  • 11
  • 82
  • 95
3

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");
crowne
  • 8,456
  • 3
  • 35
  • 50
1

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();
brabster
  • 42,504
  • 27
  • 146
  • 186
1

Your first question can be answered by looking at this question: Getting the class name from a static method in Java.

Community
  • 1
  • 1
Ray Toal
  • 86,166
  • 18
  • 182
  • 232
1

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.

Kowser
  • 8,123
  • 7
  • 40
  • 63
0

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.

andyb
  • 43,435
  • 12
  • 121
  • 150
0

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.

George
  • 1,457
  • 11
  • 26