主方法调用一个线程启动 , 每隔一定的时间执行 , 执行的内容为根据 two.txt 的内容反射调用对应的接口实现类的方法 , 其中一个实现类读取one.txt 中的字符串 , 反序列化成实体类 , tostring方法打印到 控制台实现线程正在执行时修改txt文件 , 可调用不同实现类
public class TestThread extends Thread {
@Override
public void run() {
while (true) {
try {
sleep(2 * 1000);
File writename = new File("相对路径/绝对路径");
FileReader reader = null;
reader = new FileReader(writename);
BufferedReader br = new BufferedReader(reader);
String s = br.readLine();
Info f = getInstance(s);
f.Sout();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static Info getInstance(String className) {
Info f = null;
try {
f = (Info) Class.forName(className).newInstance();
} catch (Exception e) {
e.printStackTrace();
}
return f;
}
}
public static void main(String[] args) throws ClassNotFoundException {
TestThread testThread = new TestThread();
testThread.start();
}
实体类
one.txt
{
"name":"xxx",
"age":21,
"sex":"男"
}
two.txt
public interface Info {
void Sout( );
}
public class OneImpl implements Info {
@Override
public void Sout() {
try {
FileReader reader = null;
File file = new File("绝对路径/相对路径");
reader = new FileReader(file);
BufferedReader read = new BufferedReader(reader);
String s;
StringBuffer sb = new StringBuffer();
while ((s = read.readLine()) != null) {
sb.append(s + "\n");
}
read.close();
JSONObject object = JSONObject.parseObject(String.valueOf(sb));
PojoTest o = JSONObject.toJavaObject(object, PojoTest.class);
System.out.println(o.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class TwoImpl implements Info{
@Override
public void Sout( ) {
System.out.println("我是twoimpl类里的");
}
}
承认自己写的非常不规范 ........
本人小白一个 , 欢迎各位大牛随时赐教