《Thinking in java》第四版中的例子tupeinfo/SweetShop.java存在问题,全限定名;forName()方法
2016-08-06 17:08
483 查看
在看到《Thinking in Java》中文第四版,Chapter14中的typeinfo/SweetShop好像有点问题。程序代码如下:
与文中的例子不符合,实际输出的是“Couldn't find Gum”,而不是“Loading Gum”,但是若是按照以下将程序稍作修改,就可以和文中匹配了。
try语句块中的Class.forName("Gum")改成Class.forName("typeinfo.Gum")。
执行结果如下:
我们不禁要问而那个"typeinfo.Gum"又是什么呢?
2.我们都知道每个文件都有属于自己的包名【没有创建包名的是默认包】,在传递给forName()的字符串中,我们必须使用全限定名【包含包名】。例如:在我的程序中,Gum类所在的文件是在typeinfo包中,类名是Gum,所以其全限定明便是“typeinfo.Gum”。
package typeinfo; class Candy{ static { System.out.println("Loading Candy too"); }
} class Gum{ static { System.out.println("Loading Gum"); } } class Cookie{ static { System.out.println("Loading Cookie"); } } public class SweetShop { public static void main(String [] args){ System.out.println("inside main"); new Candy(); System.out.println("After creating Candy"); try { Class.forName("Gum"); } catch (ClassNotFoundException e) { System.out.println("Couldn't find Gum"); } System.out.println("After Class.forName(\"Gum\")"); new Cookie(); System.out.println("After creating Cookie"); } }程序的输出结果如下:
与文中的例子不符合,实际输出的是“Couldn't find Gum”,而不是“Loading Gum”,但是若是按照以下将程序稍作修改,就可以和文中匹配了。
try语句块中的Class.forName("Gum")改成Class.forName("typeinfo.Gum")。
执行结果如下:
我们不禁要问而那个"typeinfo.Gum"又是什么呢?
2.我们都知道每个文件都有属于自己的包名【没有创建包名的是默认包】,在传递给forName()的字符串中,我们必须使用全限定名【包含包名】。例如:在我的程序中,Gum类所在的文件是在typeinfo包中,类名是Gum,所以其全限定明便是“typeinfo.Gum”。
相关文章推荐
- JAVA自学-20180324 反射中forName方法的classnotfound错误及cmd运行问题
- 《Thinking in Java》RMI远程方法示例代码运行是可能遇到的问题及解决方法
- DataForm中包含TabControl控件,FindNameInContent方法无法获取未选中TabItem里的控件问题
- Exception in thread "main" java.lang.NoClassDefFoundError 问题及其解决方法
- Java 的 Socket 服务器和客户端通信的例子 存在一个小问题
- java Exception in thread "main" java.lang.NoClassDefFoundError: (wrong name: 解决方法
- Can not find a java.io.InputStream with the name [downloadFile] in the invocation stack问题解决
- [Android] "Failed to find Java version for 'C:\Windows\system32\java.exe"问题的解决方法
- Thinking in Java 第四版本--第3章练习题答案--for,break,switch,case,default
- Can not find a java.io.InputStream with the name [downloadFile] in the invocation stack问题解决
- Struts2中DMI(动态方法调用)的错误问题(There is no Action mapped for namespace [/xxx] and action name [xxx!yyy] a)
- Can not find a java.io.InputStream with the name [downloadFile] in the invocation stack问题解决
- phpcms2008 信息管理 Warning: Invalid argument supplied for foreach() in 问题的解决方法
- exception in thread main java.lang.NoClassDefFoundError wrong name解决方法
- The Difference of Class.forName()、Class.forName().newInstance() and New in Java
- thinking in java的private方法,但不知道这个有什么用
- DataForm中包含TabControl控件,FindNameInContent方法无法获取未选中TabItem里的控件问题
- Can not find a java.io.InputStream with the name [downloadFile] in the invocation stack问题解决
- Java面向对象基础--类的设计及分析问题的方法---用户登录例子
- Can not find a java.io.InputStream with the name [inputStream] in the invocation stack问题解决