1. 程式人生 > 其它 >java.lang.ClassNotFoundException: SpringSkinFactory抽象工廠模式範例報錯

java.lang.ClassNotFoundException: SpringSkinFactory抽象工廠模式範例報錯

示例程式碼:

package AbstractFactory.utils;

import javax.xml.parsers.*;

import org.w3c.dom.*;

import java.io.*;

public class XMLUtil {
    //該方法用於從XML配置檔案中提取具體類類名,並返回一個例項物件
    public static Object getBean() {
        try {
            //建立文件物件
            DocumentBuilderFactory dFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = dFactory.newDocumentBuilder();
            Document doc;
            doc = builder.parse(new File("src/AbstractFactory/config/config.xml"));
            //獲取包含類名的文字節點
            NodeList nl = doc.getElementsByTagName("className");
            Node classNode = nl.item(0).getFirstChild();
            String cName = classNode.getNodeValue();
            //通過類名生成例項物件並將其返回
            Class<?> c = Class.forName(cName);
//            Class<?> c = Class.forName("AbstractFactory.factory." +cName);
            Object obj = c.newInstance();
            return obj;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}

報錯:

java.lang.ClassNotFoundException: SpringSkinFactory
	at java.net.URLClassLoader.findClass(URLClassLoader.java:387)
	at java.lang.ClassLoader.loadClass(ClassLoader.java:418)
	at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:355)
	at java.lang.ClassLoader.loadClass(ClassLoader.java:351)
	at java.lang.Class.forName0(Native Method)
	at java.lang.Class.forName(Class.java:264)
	at AbstractFactory.utils.XMLUtil.getBean(XMLUtil.java:23)
	at AbstractFactory.Client.main(Client.java:16)
Exception in thread "main" java.lang.NullPointerException
	at AbstractFactory.Client.main(Client.java:18)

原因:
缺少包名,原例的程式碼是在預設的包下面,需要加上路徑
如我的路徑

Class<?> c = Class.forName("AbstractFactory.factory." +cName);