简体   繁体   中英

Is SomeClass.class considered a constant with no runtime coupling?

Where I have the following code:

BasePlugin p = Manager.getPlugins(...);

I want to get a reference to a plugin which may not may be available.

For example, lets say I do this:

BasePlugin p = Manager.getPlugins("PluginApple");

But some time later the plugin's name is changed to "PluginPear". This will break any code which hard-coded the previous constant.

I could do this:

try {
    SomePlugin p = Manager.getPlugins(PluginApple.getName());
}
catch (ClassNotFoundException ex) {
}

Which works but what if instead Manager.getPlugins() performed its lookup based on class names rather than strings?

For example:

BasePlugin p = Manager.getPlugins(PluginApple.class);

if (p != null)
   ((PluginApple)p).doSomething())

So here's the question: I can build a jar that knows about PluginApple as long as it's available for reference in the classpath. But now lets say that PluginApple is not available at runtime. Is the value of PluginApple.class provided as a constant whose value is determined when the byte code is built? Or will I get some kind of runtime exception if the class is not available?

But now lets say that PluginApple is not available at runtime. Is the value of PluginApple.class provided as a constant whose value is determined when the byte code is built?

No. It is a class literal representing an object of type java.lang.Class . Evaluating the method invocation requires creating that object, which in turn requires loading the designated class.

Or will I get some kind of runtime exception if the class is not available?

You will get a NoClassDefFoundError . (Nice. There are a lot fewer ways to get an Error than there are to get an Exception )

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