框架的概念及用反射开发框架的原理:
java框架就是一些类和接口的集合,通过这些类和接口协调来完成一系列的程序实现。 从框架字面上也可以看出框架是什么,就是架子嘛,如:我们买的房子(毛环房)就相当于一个框架,门、窗户、是自己写的类,而锁是门上的工具,称为工具类。框架调用门,门调用工具,从这里可以看 框架、工具类的关系,框架可以提高开发效率。
// 写一个程序,这个程序能根据用户提供的类名,去执行该类中的main方法。
//普通方式
ArgumentTest.main(new String[]{"111","222","333"});
//反射方式:
String className=args[0];
Method mainMethod=Class.forName(className).getMethod("main", String[].class);
//拆包,jdk1.4语法.需要加一层
mainMethod.invoke(null, new Object[]{new String[]{"111","222","333"}});
// mainMethod.invoke(null,(Object)new String[]{"111","222","333"});jdk1.5语法。
package demo;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Collection;
import java.util.Properties;
import com.heima.day1.ReflectPoint;
public class ReflectTest2 {
public static void main(String[] args) throws Exception{
//我不也不知道要new什么样对象。
//那就让用户自己写吧
//通过流加载 配置文件。动态创建。
// Collection collection=new ArrayList();
//注意:实际开发中要要写完整的路径,完整的路径不是硬编码来的,而是运算出来的。
// InputStream ips =new FileInputStream("config.properties");
//通过类加载器加载配置文件
//InputStream ips =ReflectTest2.class.getClassLoader().getResourceAsStream("demo/config.properties");
//通过字节码的getResourceAsStream()的方法加载,其实也是调用的是类加载器的getResourceAsStream()
InputStream ips =ReflectTest2.class.getResourceAsStream("config.properties");
Properties props =new Properties();
props.load(ips);
//关闭资源,是关闭ips相关联的系统资源,ips对象是由java垃圾回收机制管理的。
ips.close();
String className=props.getProperty("className");
Collection collection=(Collection) Class.forName(className).newInstance();
ReflectPoint pt1=new ReflectPoint(3,5);
ReflectPoint pt2=new ReflectPoint(3,5);
ReflectPoint pt3=new ReflectPoint(3,5);
collection.add(pt1);
collection.add(pt2);
collection.add(pt3);
collection.add(pt1);
System.out.println(collection.size());
}
}
//辅助类
class TestArguments{
public static void main(String[] args){
for(String arg :args){
System.out.println("---"+arg+"---");
}
}
}