Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
        }
    }
}
  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?
like image 802
Alexander Farber Avatar asked Jul 15 '11 07:07

Alexander Farber


2 Answers

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.

like image 190
Petar Ivanov Avatar answered Sep 29 '22 15:09

Petar Ivanov


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");
like image 20
crowne Avatar answered Sep 29 '22 16:09

crowne