Python 官方文档:入门教程 => 点击学习
目录一、反射概述二、入门案例三、反射原理图四、反射性能测试五、Class类六、类加载总结一、反射概述 反射允许程序在运行中获取类的内部信息,例如构造器、成员变量、成员方法等
通过配置文件中的内容生成指定类的对象并调用指定方法
// 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:
}
}
}
本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注编程网的更多内容!
--结束END--
本文标题: 一篇文章带你了解一些Java反射的学习记录
本文链接: https://www.lsjlt.com/news/134391.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0