math4tots
math4tots

Reputation: 8870

Initializing a static Class variable known at compile time in Java

I want to initialize a static Class variable in Java:

public class NumberExpression {
    private static Class numberClass = Class.forName("java.lang.Number");
};

The above code segment doesn't work because Class.forName throws a ClassNotFoundException. Something like new Integer().getClass() won't work because Number is an abstract class.

I suppose I could wrap Class.forName around a static method that handles the ClassNotFoundException, but is there a more elegant/standard way of getting what I want?

Edit:

(class "Number" changed to "java.lang.Number")

Upvotes: 1

Views: 125

Answers (2)

Francisco Spaeth
Francisco Spaeth

Reputation: 23893

It doesn't work because the class Number doesn't exist. What you meant was java.lang.Number.

You could try something like:

public class NumberExpression {
    private static Class numberClass;
    static {
        try {
            numberClass = Class.forName("java.lang.Number");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
};

But this just makes sense when the class that you are trying to load is dynamic, otherwise you could use the class it self (i.e. Number.class)

Upvotes: 5

Savvas Dalkitsis
Savvas Dalkitsis

Reputation: 11592

Why don't you do :

private Class numberClass = Number.class;

Upvotes: 4

Related Questions