黑马程序员技术交流社区
标题:
程序运行无法通过 反射的问题 求解
[打印本页]
作者:
wangyuyus
时间:
2013-11-10 19:15
标题:
程序运行无法通过 反射的问题 求解
import java.io.*;
import java.lang.reflect.Method;
import java.util.Properties;
public class Text7 {
/**
写一个Properties格式的配置文件,
用反射 的方式运行run方法
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
read();
}
public static void read() throws Exception{
Properties prop = new Properties();
File file = new File("read.properties");
if(!file.exists())
try {
file.createNewFile();
} catch (IOException e) {
throw new RuntimeException("创建失败");
}
FileInputStream fis = new FileInputStream(file);
System.out.println("1");
prop.setProperty("name","DemoClass");
prop.load(fis);
FileOutputStream fos = new FileOutputStream(file);
prop.store(fos, "");
String cls=prop.getProperty("name");
System.out.println(cls);
if(cls!=null){
System.out.println("3");
//Class clazz =cls.getClass();
System.out.println("4");
Method mod =cls.getClass().getMethod("run",null);//这里 无法通过
System.out.println("5");
mod.invoke(cls, null);
System.out.println("6");
}
}
}
class DemoClass {
public void run()
{
System.out.println("welcome to heima!");
}
}
作者:
敗唫①輩ふ
时间:
2013-11-10 20:03
本帖最后由 敗唫①輩ふ 于 2013-11-11 11:10 编辑
public class Demo1 {
public static void main(String[] args) throws Exception {
Demo1.read();
}
public static void read() throws Exception{
Properties p=new Properties();
InputStream is=new FileInputStream(new File("src/com/itheima/read.properties"));
p.load(is);
is.close();
String className=p.getProperty("name");
DemoClass name=(DemoClass)Class.forName(className).newInstance();
name.run();
}
}
class DemoClass {
public void run()
{
System.out.println("welcome to heima!");
}
}
兄弟,没那么复杂,而且你的输出流是干什么的,没有用。通过String className=p.getProperty("name"); 得到name以后通过反射就得到这个类了,然后调用方法就ok了。你可以试一下上面这个改过之后的。
作者:
◇_逞强是最狼狈
时间:
2013-11-11 11:13
顶楼上{:soso_e130:}
作者:
黄炳期
时间:
2013-11-11 11:55
如果问题已经解决,请及时修改主题为“提问结束”。
修改主题的方法链接
http://bbs.itheima.com/thread-89313-1-1.html
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2