1

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")

2 Answers 2

5

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)

Sign up to request clarification or add additional context in comments.

6 Comments

Yes, you're right. But even after I change it, the compiler still complains that the exception needs to be caught.
@math4tots: Then catch the exception!
@OliCharlesworth How? it's a static variable, so I don't know where I should set it. From what I understand, I don't think I can catch exceptions in a class body...
@math4tots: please take a look into my update ;) What I'm doing there is creating a static block, and within this static block the numberClass is set.
That is really cool that you can do that. However I think Dalkitsis had exactly the solution I needed.
|
4

Why don't you do :

private Class numberClass = Number.class;

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.