时间:2021-11-30 09:50:57 | 栏目:JAVA代码 | 点击:次
通过配置文件中的内容生成指定类的对象并调用指定方法
// re.properties className=com.javalearn.reflect.Cat methodName=hi
public class Cat {
private String name = "招财猫";
public void hi() {
System.out.println("hi:" + this.name);
}
}
public class ReflectionDemo {
public static void main(String[] args) throws Exception {
// 1.properties对象加载配置文件
Properties properties = new Properties();
properties.load(new FileInputStream("src/main/resources/re.properties"));
String className = properties.getProperty("className");
String methodName = properties.getProperty("methodName");
System.out.println("类名:" + className);
System.out.println("方法名:" + methodName);
// 2.根据类名获取Class类对象
// 获取Class对象的三种方式:
// 1.类名.class
// 2.对象.getClass()
// 3.Class.forName(类名)
Class cls = Class.forName(className);
// 3.生成实例对象
Object o = cls.newInstance();
// 4.获取方法
Method declaredMethod = cls.getDeclaredMethod(methodName);
// 5.方法.invoke(对象)
declaredMethod.invoke(o);
// 6.反射涉及的其他类
// 6.1Field成员变量
Field name = cls.getDeclaredField("name");
name.setAccessible(true); //private属性需暴力反射
System.out.println(name.get(o));
// 6.2Constructor构造器
Constructor constructor = cls.getConstructor(); //方法参数类型与构造器的参数类型一致,不写就是无参构造器
Object o1 = constructor.newInstance();
System.out.println(o1);
}
}
Java程序执行的三个阶段

反射可以做哪些事?
在运行时:
反射基本上是解释执行,性能差
public class PerformanceDemo {
public static void main(String[] args) throws Exception {
tradition();
reflect();
}
private static void reflect() throws Exception {
Class cls = Class.forName("com.sankuai.yangjin.javalearn.reflect.Cat");
Object o = cls.newInstance();
Method hi = cls.getMethod("hi");
long start = System.currentTimeMillis();
for (int i = 0; i < 10000; i++) {
hi.invoke(o);
}
long end = System.currentTimeMillis();
System.out.println("反射耗时:" + (end - start));
}
private static void tradition() {
Cat cat = new Cat();
long start = System.currentTimeMillis();
for (int i = 0; i < 10000; i++) {
cat.hi();
}
long end = System.currentTimeMillis();
System.out.println("传统耗时:" + (end - start));
}
}
优化方式:
Method、Field、Constructor对象都有setAccessible()方法,可以将参数设置为true,表示在使用反射时取消访问检查,效果也就一般般
反射是Java实现动态语言的关键,通过反射实现类动态加载
将下面一段代码通过javac 编译时,因为并没有Dog类,所以编译失败;但当前同样没有Person类,却不会由于没有Person类而导致编译失败,因为是动态加载,当出现case "2"时才会加载该类
public class LoadDemo {
public static void main (String[] args) throws Exception {
Scanner scanner = new Scanner(System.in);
String num = scanner.next();
switch (num) {
case "1":
// 静态加载
Dog dog = new Dog();
break;
case "2":
// 反射,动态加载
Class person = Class.forName("Person");
break;
default:
}
}
}