package com.itheima;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.util.Properties;
/**
* 6、 已知一个类,定义如下:
package cn.itcast.heima;
public class DemoClass {
public void run()
{
System.out.println("welcome to heima!");
}
}
(1) 写一个Properties格式的配置文件,配置类的完整名称。
(2) 写一个程序,读取这个Properties配置文件,获得类的完整名称并加载这个类,用反射 的方式运行run方法。
*
*
* @author
*
*/
public class Test6 {
/*
public static void main(String args[]) throws FileNotFoundException, IOException, ClassNotFoundException, IllegalArgumentException, SecurityException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, InstantiationException {
Properties prop = new Properties();
InputStream ips = Test6.class.getResourceAsStream("/exam/src/com/itheima/config.properties");
prop.load(ips);
ips.close();
//获取配置文件中类的对象
String className = prop.getProperty("className");
Class<?> clazz = Class.forName(className);
clazz.getMethod("run", null).invoke(clazz.newInstance());
}
*/
public static void main(String[] args){
Properties p = new Properties();
Class<?> demo = null;
DemoClass dc = null;
try{
p.load(new FileReader("src/com/itheima/config.properties"));
String className = p.getProperty("className");
demo = Class.forName(className);
dc = (DemoClass)demo.newInstance();
dc.run();
}catch(Exception e){
e.printStackTrace();
}
}
}
出错了:
java.lang.ClassNotFoundException: exam.src.com.itheima.DemoClass
at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:252)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:320)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:169)
at com.itheima.Test6.main(Test6.java:54)
求大神指教啊
|
|