当前位置:网站首页>通过反射获取Class对象的四种方式
通过反射获取Class对象的四种方式
2022-08-05 05:21:00 【洒家肉山大魔王】
Java反射机制
反射:通过反射我们可以获取任意一个类的所有属性和方法,还可以调用这些方法和属性。
反射的优缺点
优点 :可以让代码更加灵活、为各种框架提供开箱即用的功能提供了便利
缺点 :让我们在运行时有了分析操作类的能力,这同样也增加了安全问题。
比如可以无视泛型参数的安全检查(泛型参数的安全检查发生在编译时)。
另外,反射的性能也要稍差点,不过,对于框架来说实际是影响不大的。
如果我们动态获取到这些信息,我们需要依靠 Class 对象。Class 类对象将一个类的方法、变量等信息告诉运行的程序。
四种获取 Class 对象的方式
通过
Class.forName()
传入类的全路径获取通过对象实例instance.getClass()获取
通过类加载器ClassLoader.loadClass()根据类的全路径获取
通过具体的实例对象获取
举个栗子
/**
* 通过反射获取Class对象的4中方式
*/
@Test
public void reflectGetMethod_Test() {
try {
String classPath = "com.hl.magic.items.day20.reflection.ReflectiveDemo";
Class<?> forName = Class.forName(classPath);
LOGGER.debug("[1]根据类全路径获取当前类的路径: {}", forName.getName());
String name = ReflectiveDemo.class.getName();
LOGGER.debug("[2]-根据类对象来获取当前类的路径: {}", name);
ReflectiveDemo reflectiveDemo = new ReflectiveDemo();
Class<? extends ReflectiveDemo> aClass = reflectiveDemo.getClass();
LOGGER.debug("[3]根据对象实例获取当前类的路径: {}", aClass.getName());
Class<?> aClass1 = ClassLoader.getSystemClassLoader().loadClass(classPath);
LOGGER.debug("[4]根据类加载器获取当前类的路径: {}", aClass1.getName());
// 根据类的path获取对应的属性
ReflectiveDemo reflectiveDemo1 = (ReflectiveDemo) forName.newInstance();
String userName = reflectiveDemo1.getUserName();
LOGGER.debug("获取反射对象的属性 : [{}]", userName);
} catch ( ClassNotFoundException | InstantiationException | IllegalAccessException e) {
e.printStackTrace();
}
}
输出:
[main] DEBUG com.hl.magic.items.day20.reflection.ReflectiveDemo - [1]根据类全路径获取当前类的路径: com.hl.magic.items.day20.reflection.ReflectiveDemo
[main] DEBUG com.hl.magic.items.day20.reflection.ReflectiveDemo - [2]-根据类对象来获取当前类的路径: com.hl.magic.items.day20.reflection.ReflectiveDemo
[main] DEBUG com.hl.magic.items.day20.reflection.ReflectiveDemo - [3]根据对象实例获取当前类的路径: com.hl.magic.items.day20.reflection.ReflectiveDemo
[main] DEBUG com.hl.magic.items.day20.reflection.ReflectiveDemo - [4]根据类加载器获取当前类的路径: com.hl.magic.items.day20.reflection.ReflectiveDemo
[main] DEBUG com.hl.magic.items.day20.reflection.ReflectiveDemo - 获取反射对象的属性 : [小明]
通过类加载器获取 Class 对象不会进行初始化,意味着不进行包括初始化等一系列步骤,静态代码块和静态对象不会得到执行。
边栏推荐
- 正则表达式小实例--去掉字符串中间和两边的空格
- spark source code - task submission process - 2-YarnClusterApplication
- Remembering my first CCF-A conference paper | After six rejections, my paper is finally accepted, yay!
- The problem of redirecting to the home page when visiting a new page in dsf5.0
- 网络层协议介绍
- This is indeed the best article on microservice architecture I have read!
- [Day6] File system permission management, file special permissions, hidden attributes
- [Day5] Soft and hard links File storage, deletion, directory management commands
- dsf5.0新建页面访问时重定向到首页的问题
- I217-V network disconnection problem in large traffic under openwrt soft routing
猜你喜欢
静态路由
【Day1】VMware软件安装
错误类型:反射。ReflectionException:无法设置属性“xxx”的“类”xxx”与价值“xxx”
network issue?Service packet loss?This is enough
Hard Disk Partitioning and Permanent Mounting
【Machine Learning】1 Univariate Linear Regression
单臂路由实验和三层交换机实验
入门文档01 series按顺序执行
OpenCV3.0 is compatible with VS2010 and VS2013
Getting Started Doc 06 Adding files to a stream
随机推荐
vim教程:vimtutor
[Day6] File system permission management, file special permissions, hidden attributes
LeetCode Interview Questions
入门文档01 series按顺序执行
有哪些事情是你做了运维才知道的?
入门文档06 向流(stream)中添加文件
Cloud computing - osi seven layers and TCP\IP protocol
What's the point of monitoring the involution of the system?
LeetCode面试题
静态路由
VRRP原理及命令
【Day8】Knowledge about disk and disk partition
深度 Zabbix 使用指南——来自惨绿少年
spark source code - task submission process - 1-sparkSubmit
ACL 和NAT
Spark source code-task submission process-6.1-sparkContext initialization-create spark driver side execution environment SparkEnv
time complexity and space complexity
Unity realizes first-person roaming (nanny-level tutorial)
Operation and maintenance engineer, come and pick up the wool
交换机原理