反射:框架(半成品软件)设计的灵魂
**加declared和不加declared的区别:**输出所有类型的成员变量(method) VS 输出public类型的成员变量(method)
具体的简单框架案例:
public class Writeframe {
public static void main(String[] args) throws Exception {
//step1:配置文件,并加载配置文件
Properties pro=new Properties();
//Java class.getClassLoader().getResource("")获取资源路径
ClassLoader classLoader = Writeframe.class.getClassLoader();
InputStream is = classLoader.getResourceAsStream("pro.properties");
pro.load(is);//从输入字节流读取属性列表(键和元素对)。
//step2:获取配置文件中定义的数据
String className = pro.getProperty("className");//获取建所对应的值:类名--字符串
String methodName = pro.getProperty("methodName");//方法名:字符串
//step3:加载类进内存
Class cls = Class.forName(className);//通过全类名获取class对象
Object o = cls.newInstance();
Method method = cls.getMethod(methodName);//感觉需要传参的情况和不需要传参的情况下有所区别(后续学习)
method.invoke(o);//配置文件中的Person对象类的eat()方法被执行
}
}
配置文件内容:
className=Fanshe_frame.Person methodName=eat
API文档的生成(shift+右键:打开powershell: 输入 javadoc xxx.java):xxx.index文件
注释:本质上是接口
具体的简单框架案例:
@Pro(className = "Zhujie.Man",methodName = "show")
public class Writeframe {
public static void main(String[] args) throws Exception {
//step1:解析注释
Class writeframeClass = Writeframe.class;
//step2:获取注释对象(助手本质也是个接口!!!)
Pro an = writeframeClass.getAnnotation(Pro.class);
//step3:调用注释对象的抽象方法
String cN=an.className();
String mN = an.methodName();
Class cls=Class.forName(cN);
Object obj = cls.newInstance();//相当于构造方法赋值
Method method = cls.getMethod(mN);
method.invoke(obj);
}
}
@Target(value={ElementType.TYPE})//这个注解只能作用于类上
@Retention(RetentionPolicy.RUNTIME)//这个注解不能少,需要被JVM读取到
public @interface Pro {
String className();
String methodName();
}



