有时我会收到错误(异常):
java.lang.IllegalStateException: Dispatch not hooked to windows memory
这是什么意思?如何预防?
这是导致此错误的示例代码:
import com.jacob.activeX.*;
import com.jacob.com.*;
public class Hooked {
public static void main(String[] args) {
ActiveXComponent e = new ActiveXComponent("Excel.Application");
ActiveXComponent sh = new ActiveXComponent(
e.getProperty("ActiveSheet").toDispatch());
System.out.println(sh.getPropertyAsString("Name"));
}
}
最佳答案
这意味着使用 vba 语法的 Dispatch
= Nothing
是空的。与使用 new Dispatch()
收到的调度相同。不幸的是,Jacob 1.17 没有提供任何方法来显式检查 Dispatch 是否为空。所以我看到了 3 种可能的解决方案:
1) 在从 COM 调用接收到 Variant 后,在将其转换为 Dispatch 之前使用 Variant.isNull()
。所以它需要额外的一行:
Variant vsh = e.getProperty("ActiveSheet");
if (vsh.isNull()) {
System.out.println("Null dispatch received.");
}
ActiveXComponent sh = new ActiveXComponent(vsh.toDispatch());
2) 首次使用可疑Dispatch时捕获IllegalStateException
。
3) 编写自定义 isNull(Dispatch d)
函数
public static boolean isNull(Dispatch d)
{
try {
Dispatch.call(d, "");
}
catch (IllegalStateException ise) {
return true;
}
catch (ComFailException cfe) {
// that's ok, we didn't expect this call to succeed
}
return false;
}
在问题的具体示例中,调用只是一个错误,因为如果没有打开或创建工作簿,Excel 就没有 ActiveSheet。
关于jacob - 调度未挂接到 Windows 内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12871152/