Class.forName()报 classnotfoundexception 错误解决办法

package CreationalPattern.FactoryMethod;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;

/**
 * XML工具类
 * Created by Dennis on 2018/6/14.
 */
public class XMLUtil {
    public static Object getBean() {
        try {
            //Create document object
            DocumentBuilderFactory dFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = dFactory.newDocumentBuilder();
            Document doc;
            doc = builder.parse(new File("src/CreationalPattern/FactoryMethod/config.xml"));

            //get the text node including a class name
            NodeList nl = doc.getElementsByTagName("className");
            Node classNode = nl.item(0).getFirstChild();
            String cName = classNode.getNodeValue();

            //Create and return an instance
            Class c = Class.forName("CreationalPattern.FactoryMethod."+cName);
            Object obj = c.newInstance();
            return obj;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}

Class c = Class.forName("CreationalPattern.FactoryMethod."+cName);

forname(这里面的要包含包名和类名,不然就会报 ClassNotFoundException 错误,因为通过反射实例化类时传递的类名称必须是全路径名称

你可能感兴趣的:(日常bug)