有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java是一个类。类被视为没有运行时耦合的常量?

其中我有以下代码:

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

我想获得一个可能不可用的插件的引用

例如,假设我这样做:

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

但过了一段时间,插件的名称改为“PluginPear”。这将中断硬编码前一个常量的任何代码

我可以这样做:

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

如果Manager.getPlugins()根据类名而不是字符串执行其查找,那会怎么样

例如:

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

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

所以这里有一个问题:我可以构建一个知道PluginApple的jar,只要它在类路径中可供参考。但是现在让我们假设PluginApple在运行时不可用。PluginApple.class的值是否作为常量提供,其值是在生成字节码时确定的?或者如果类不可用,我会得到某种运行时异常吗


共 (1) 个答案

  1. # 1 楼答案

    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?

    不是。它是一个类文本,表示java.lang.Class类型的对象。评估方法调用需要创建该对象,这反过来需要加载指定的类

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

    你会得到一个NoClassDefFoundError。(很好。获得Error的方法比获得Exception的方法少得多)