今天在学习工厂模式,讲到解耦时,自己照着敲代码却一直抛出ClassNotFoundException的异常,百思不得其解,经过反反复复的测试才发现自己犯了一个特别低级的错误。
抛出异常如下:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16java.lang.ClassNotFoundException: swu/twj/dao/impl/UserDaoImpl; at java.lang.Class.forName0(Native Method) at java.lang.Class.forName(Class.java:264) at swu.twj.factory.BeanFactory.getBean(BeanFactory.java:24) at swu.twj.service.impl.UserServiceImpl.<init>(UserServiceImpl.java:12) at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) at java.lang.reflect.Constructor.newInstance(Constructor.java:423) at java.lang.Class.newInstance(Class.java:442) at swu.twj.factory.BeanFactory.getBean(BeanFactory.java:24) at swu.twj.ui.Client.main(Client.java:9) Exception in thread "main" java.lang.NullPointerException at swu.twj.service.impl.UserServiceImpl.saveUser(UserServiceImpl.java:16) at swu.twj.ui.Client.main(Client.java:10)
工厂类代码如下:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26public class BeanFactory { private static Properties props; static { try { props = new Properties(); InputStream in = BeanFactory.class.getClassLoader().getResourceAsStream("bean.properties"); props.load(in); } catch (Exception e) { throw new ExceptionInInitializerError("初始化properties失败"); } } public static Object getBean(String beanName) { Object bean = null; try { String beanPath = props.getProperty(beanName); System.out.println(beanPath); bean = Class.forName(beanPath).newInstance(); } catch (Exception e) { e.printStackTrace(); } return bean; } }
反复检查后发现工厂类确实没有问题,于是写了一个方法用来测试:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17public class Test { public static void main(String[] args) throws Exception { Properties props = new Properties(); InputStream in = Test.class.getClassLoader().getResourceAsStream("bean.properties"); props.load(in); String value1 = props.getProperty("userDao"); String value2 = props.getProperty("userService"); System.out.println("value1 = " + value1); System.out.println("value2 = " + value2); //System.out.println(Class.forName(value1).newInstance()); } }
但是一旦放开了System.out.println(Class.forName(value1).newInstance())来创建对象的时候就会报错:
经过反反复复思考后终于发现了问题所在!
原来是在配置properties文件的时候,在每行末尾都加了分号( ; ),导致输出value的时候也在末尾加上了分号,所以才报出了异常
只需把分号删除,问题即可解决:
所以在配置properties文件的时候一定要记住不能在末尾加上分号,就是最基本的键值对,分号会被当做value的值算进去。
最后
以上就是灵巧往事最近收集整理的关于工厂模式解耦时抛出异常java.lang.ClassNotFoundException的全部内容,更多相关工厂模式解耦时抛出异常java内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复