ERROR: JDWP Unable to get JNI 1.2 environment, jvm->GetEnv() return code = -2
转载自:http://andy820303.spaces.live.com/Blog/cns!66AADE4958C27A0C!264.entry
ERROR: JDWP Unable to get JNI 1.2 environment, jvm->GetEnv() return code = -2
今天早上开始编译书中的一个小例子。发现了这个错误,很奇怪,因为直接用jdk编译就没有问题,可是如果用eclipse编译,就会出现这个错误,但是一样可以生成.class文件,并且控制台的输出也正常。
我用的就是下面的这个例子:
public class CountInstances {
? private static int numInstances = 0;
? protected static int getNumInstances() {
? return numInstances;
? }
? private static void addInstance() {
? numInstances++;
? }
? CountInstances() {
? CountInstances.addInstance();
? }
? public static void main(String[] arguments) {
? System.out.println("Starting with " +
? CountInstances.getNumInstances() + " instances");
? for (int i = 0; i < 10; ++i)
? new CountInstances();
? System.out.println("Created " +
? CountInstances.getNumInstances() + " instances");
? }
}
上网搜了一下,原因是:eclipse和jdk1.6的版本冲突 sun的网站上有 http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6476706 目前还没有解决。
还发现了一段精彩的评论,如下:
经过我仔细的查阅Java Doc,发现其中有这么一段话:
http://download.java.net/jdk6/docs/api/java/io/Console.html
"Whether a virtual machine has a console is dependent upon the underlying platform and also upon the manner in which the virtual machine is invoked. If the virtual machine is started from an interactive command line without redirecting the standard input and output streams then its console will exist and will typically be connected to the keyboard and display from which the virtual machine was launched. If the virtual machine is started automatically, for example by a background job scheduler, then it will typically not have a console." ">http://download.java.net/jdk6/docs/api/java/io/Con..."
翻译一下:
虚拟机是否有一个控制台Console取决于所依赖的平台和虚拟机解析该方法的方式。如果虚拟机是从一个交互式的命令行中启动的,而没有重定向标准输入和输出流,那么虚拟机会自动的连接到键盘作为标准输入,并且把启动虚拟机的地方作为标准输出。如果虚拟机是自动启动的,例如通过后台的一个任务计划,那么典型的情况就是没有Console控制台……。
于是,思考一下我们运行上面程序的地点——Eclipse等集成开发环境,这对于上面描述中的把启动虚拟机的地方作为标准输出来说是不合适的,这里的Console()返回的默认情况下是Null,于是就产生了上面的出错信息。(也许未来Eclipse会有所改进吧)
怎么解决该问题呢?这里提供两条思路给大家(已经实际操作过,可以实现功能的正常运作)
1、使用命令行进行运行,编译可以使用集成开发环境。这样可以完成标准输出。
2、在程序中重定向标准输出到其他的设备或者方式(例如写到文本文件),这样也可以“比较不方便的”完成该功能。
总结:
重申!!文档很重要,特别是官方文档和一些说明书性质的文献资料。预期看什么XX天精通YY技术,还不如首先把官方的文档通读一遍。推荐Java Doc和MSDN Library。
看来找到问题所在了,不过还有网友的方法是在main函数后面加个System.exit(0);
果然行得通,可是这是为什么呢?System.exit(0)于return有什么区别的,还得上网查查看:
有人说System.exit(0)是用于中止多线程,也就是所有这个程序生成的所有线程都要中止。但是它在这段程序中的作用我还是搞不清楚。下面对于system.exit(0)的解释值得参考。
return和System.exit(0)的不同[转贴]
如果我在public static void main(String[] args)??
中的某一行程式加上return;使JVM得跳main()??
也就是束程式,那和System.exit(0)有何不同呢?
因是在 public static void main(String[] args) 中 return...??
? 所以其效果等同於 System.exit( ) ...??
? 但是只要 method 之中...??
? 那就明的不同....??
? 也可以...??
? return => 回到上一...??
? System.exit() => 回到最上...
?
System.exit(0) 是一中JVM的指令吧
finally block遇到System.exit(0)之後都有法行了
System.exit() 看,其不管放什值,程式都被止,
但值可以被呼叫它的程式捕捉。例如我可以在 Windows 一支批次,
用行支程式,程式行完成或中後,exit() 的就被出,
接著我就可以判 ERRORLEVEL (出的值放在) 定下一步要做什
了。