对于之前的 具体反射机制操作都停留在文字叙述
以下是代码示例会更直观一点
src下的spring.txt 里就是反射的内容—— 类名 方法名
因此也不需要重新编译,只需要修改配置文件spring.txt,再运行即可
@SuppressWarnings({"rawtypes","unchecked"})
public static void main(String[] args) throws Exception{
File springConfigFile=new File("D:\\Jproject\\theFirst\\src\\spring.txt");
Properties springConfig=new Properties();
springConfig.load(new FileInputStream(springConfigFile));
String className =(String) springConfig.get("class");
String methodName= (String)springConfig.get("method");
Class cla= Class.forName(className);
Method m=cla.getMethod(methodName);
Constructor c=cla.getConstructor();
Object service=c.newInstance();
m.invoke(service);
}
@SuppressWarnings({“rawtypes”,“unchecked”})——注解
该批注的作用是给编译器一条指令,告诉它对被批注的代码元素内部的某些警告保持静默。
这种是抑制多种类型的警告
对于配置文件的格式问题——后缀格式只是为了更好的可读性,config代表是配置,其实txt,或者你自定义的文件格式也可以。
这里需要补充的除了代码 还有properties类的补充 之前在io中有涉及 但是没怎么注意
properties意为性质的意思 主要是通过这个类的实例去调用方法 来对配置文件进行操作
日后接触spring框架 会更方便更易理解