本帖最后由 杜正冬 于 2012-11-28 00:25 编辑
package com.itheima;
import java.io.FileInputStream;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Properties;
public class Test8 {
public static String value = null;
public static String fileName = "/itheima.Properties";
static {
try {
InputStream f = Test8.class
.getResourceAsStream(fileName);// 这里有人用new
// FileInputStream(fileName),不过这种方式找不到配置文件。有人说是在classes下,我调过了,不行。
System.out.println(f);
Properties p = new Properties();
p.load(f);
System.out.println(" dssdd" + p);
f.close();
if (p.containsKey("key")) {
value = p.getProperty("key");
System.out.println(" dsd"+value);
}
} catch (Exception e) {
System.out.println(" dsd");
}
}
public static void main(String[] args) throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException, InstantiationException {
Class clazz;
Method method;
try {
clazz = Class.forName("com.itheima."+Test8.value);
method = clazz.getMethod("run", null);
method.invoke(clazz.newInstance(), null);
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println("" +Test8.value);
try {
} catch (SecurityException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try{
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/*
* 已知一个类,定义如下:
*
* package cn.itcast.heima; public class DemoClass { public void run() {
* System.out.println("welcome to heima!"); } } (1)
* 写一个Properties格式的配置文件,配置类的完整名称。 (2)
* 写一个程序,读取这个Properties配置文件,获得类的完整名称并加载这个类,用反射 的方式运行run方法。
*/
}
|
|