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?

7 Answers 7

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.

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");
0
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();
1

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

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.

2
  • Numbers.class.getClass() returns Class<Class<?>> not Class<Numbers>. He should use Numbers.class.getName()
    – helios
    Jul 15, 2011 at 7:45
  • I'm sorry, but this is useless then. I can just hardcode the String "Numbers" in my program. Jul 15, 2011 at 8:29
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.

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.