简体   繁体   中英

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

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 (ie Number.class )

你为什么不做:

private Class numberClass = Number.class;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM