[quote]
[b]运行结果:1279024660175[/b]
[/quote]
package com.java.day01;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Method;
public class ReflectTest {
//反射应用;
//创建文件,并定义类对象;
public void createFile(String str) throws Exception{
FileOutputStream out = new FileOutputStream(new File(str));
String s = "java.util.Date \ngetTime";
byte[] b = s.getBytes();
out.write(b);
out.close();
out.flush();
}
//反射成对象;
public void invokeObject(String str) throws Exception{
BufferedReader in = new BufferedReader(
new InputStreamReader(
new FileInputStream(str)));
String s1 = in.readLine().trim();//注意要去掉首尾的空格,否则会发生找不到类文件异常
String s2 = in.readLine().trim();
Class cl = Class.forName(s1);//找到类文件;
Object o = cl.newInstance();//得到类对象;
Method m = cl.getMethod(s2,null);//取得方法
Object obj = m.invoke(o, null);//反射成为对象;
if(obj != null){
System.out.println("运行结果:"+obj);
}
}
public static void main(String[] args) throws Exception{
String str ="/home/soft22/Desktop/abc.txt";
ReflectTest t = new ReflectTest();
t.createFile(str);
t.invokeObject(str);
}
}
[b]运行结果:1279024660175[/b]
[/quote]