- 反射:即通过外部文件的配置,在不修改源码的条件下,控制程序。也符合设计模式的ocp原则(开闭原则:不修改源码,扩容功能)
- 示例如下根据配置文件re.properties指定信息,创建Cat对象并调用hi方法
- classfullpath=com.elf.Cat
- method =hi
package com.elf.reflection.question;
import com.elf.Cat;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Properties;
@SuppressWarnings({"all"})
public class ReflectionQuestion {
public static void main(String[] args) throws IOException, ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
Properties properties = new Properties();
properties.load(new FileInputStream("src\\re.properties"));
String classfullpath = properties.get("classfullpath").toString();
String methodName = properties.get("method").toString();
System.out.println("classfullpath=" + classfullpath);
System.out.println("method=" + methodName);
Class cls = Class.forName(classfullpath);
Object o = cls.newInstance();
System.out.println("o的运行类型"+o.getClass());
Method method1 = cls.getMethod(methodName);
System.out.println("=============");
method1.invoke(o);
}
}
classfullpath=com.elf.Cat
method=cry
package com.elf;
public class Cat {
private String name = "招财猫";
public void hi() {
System.out.println("hi" + name);
}
public void cry() {
System.out.println("cry" + name);
}
}