黑马程序员技术交流社区
标题:
看到一篇帖子 可是运行出错 求解决
[打印本页]
作者:
王红霞
时间:
2012-7-24 19:52
标题:
看到一篇帖子 可是运行出错 求解决
本帖最后由 王红霞 于 2012-7-25 18:53 编辑
class Test{
public void run(){
System.out.println("welcome to heima!");
}
}
public class PropertiesDemo {
public static void main(String[] args)throws Exception{
InputStream in= PropertiesDemo.class.getClassLoader()
.getResourceAsStream("prop.properties");
Properties pro = new Properties();
pro.load(in);//文件正常配置,可是这个出错?
in.close();
String className = pro.getProperty("prop");
Class c=Class.forName(className);
Object ob=c.newInstance();
Method m=c.getMethod("run");
m.invoke(ob);
/* Enumeration en = pro.propertyNames();
while (en.hasMoreElements()) {
String key = (String) en.nextElement();
String Property = pro.getProperty(key);
System.out.println(key + Property);
*/
// }
}
}
作者:
王志明
时间:
2012-7-24 20:08
本帖最后由 Mrng8888 于 2012-7-24 20:10 编辑
我估计很有可能是你的properties文件里面的prop的value写错了,一定要写完整类名
package test1;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.util.Properties;
public class PropertiesDemo {
//如果是独立的一个类就是 包名.类名
//如果是静态内部类,就是 包名.外层类名$类名,比如下面这个Test类
//如果是一个普通的内部类,不好意思,不能直接对他实例化,内部类实例要依赖外部类实例
public static class Test {
public void run() {
System.out.println("welcome to heima!");
}
}
public static void main(String[] args) throws Exception {
InputStream in = PropertiesDemo.class.getClassLoader()
.getResourceAsStream("prop.properties");
Properties pro = new Properties();
pro.load(in);
in.close();
String className = pro.getProperty("prop");
Class c = Class.forName(className);
Object ob = c.newInstance();
Method m = c.getMethod("run");
m.invoke(ob);
}
}
properties文件
prop=test1.PropertiesDemo$Test
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2