java.lang.ClassNotFoundException: HaierTVFactory

今天写了一个类如下:

package com.factory.method;

import java.io.File;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

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

public class XMLUtilTV {
	//该方法用于从XML配置文件中提取品牌名称,并返回该品牌的名称
	public static Object getBean() {
		try{
			//创建文档对象
			DocumentBuilderFactory dFactory = DocumentBuilderFactory.newInstance();
			DocumentBuilder builder = dFactory.newDocumentBuilder();
			Document doc;
			doc = builder.parse(new File("src\\com\\factory\\method\\configTV.xml"));
			
			//获取包含品牌名称的文本节点
			NodeList nl = doc.getElementsByTagName("className");
			Node classNode = nl.item(0).getFirstChild();
			String className = classNode.getNodeValue();

			//通过类名生成实例对象并将其返回
			Class c = Class.forName(className);
			Object obj = c.newInstance();
			return obj;
			
		} catch(Exception e) {
			e.printStackTrace();
			return null;
		}
	}
}


报错:

java.lang.ClassNotFoundException: HaierTVFactory
	at java.net.URLClassLoader$1.run(Unknown Source)
	at java.security.AccessController.doPrivileged(Native Method)
	at java.net.URLClassLoader.findClass(Unknown Source)
	at java.lang.ClassLoader.loadClass(Unknown Source)
	at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
	at java.lang.ClassLoader.loadClass(Unknown Source)
	at java.lang.Class.forName0(Native Method)
	at java.lang.Class.forName(Unknown Source)
	at com.factory.method.XMLUtilTV.getBean(XMLUtilTV.java:28)
	at com.factory.method.Client.main(Client.java:8)

找了半天才找到错误:

我的HaierTVFactory类放在了com.factory.method包里了,直接Class c = Class.forName(className);无法找到类,所以要加上包名,如下形式:

Class c = Class.forName(“com.factory.method." + className);

OK!!!

你可能感兴趣的:(forName)