package cn.itcast.day1;
import java.io.File;
import java.io.InputStream;
import java.util.Properties;
public class ReflectTest {
public static void main(String[] args)throws Exception {
//笔记本电脑使用usb设备
NoteBook computer = new NoteBook();
computer.run();
//关联配置文件
/*File file = new File("usb.properties");
FileInputStream fis = new FileInputStream(file);*/
InputStream ips = ReflectTest.class.getResourceAsStream("usb.properties");
//将配置文件信息缓存到集合中,记住配置文件中新添加的类名需要加上具体的包名路径
Properties ps = new Properties();
ps.load(ips);
System.out.println(ps.size());
for(int x=1;x<=ps.size();x++){
String className = ps.getProperty("usb"+x);//获取配置文件中类名
Class clazz=Class.forName(className);//获取类的Class对象
USB usb = (USB)clazz.newInstance();//得到类实例
computer.useUSB(usb);//开始使用
}
ips.close();//关流
}
}
//usb接口
interface USB{
void open();
void close();
}
//笔记本电脑
class NoteBook{
public void run(){
System.out.println("NoteBook is run!");
}
public void useUSB(USB usb){
if(usb!=null){
usb.open();
usb.close();
}
}
}
//鼠标
class MouseUSB implements USB{
public void open(){
System.out.println("Mouse is use");
}
public void close(){
System.out.println("Mouse is close");
}
}
//键盘
class KeyUSB implements USB{
public void open(){
System.out.println("Key is use");
}
public void close(){
System.out.println("Key is close");
}
} |