当前位置:网站首页>Reflection (II)
Reflection (II)
2022-07-07 07:08:00 【Cold Snowflakes】
Static loading and dynamic loading
Static loading : Load related classes at compile time , If it is not found, an error is reported .
Dynamic loading : Load the required classes at runtime .
Reflection is dynamic loading , Only when it is executed , To load the class .
public class Main{
public static void main(String args[]) throws ClassNotFoundException{
// Static loading , Load when compiling , If you don't find it, you will report an error , Strong dependence
Cat cat = new Cat();
// Dynamic loading , Don't worry about it when compiling , I won't check Whether the loaded class exists
// The code will not be loaded until it is actually run and executed
Class.forName("com.itheima.Cat");
}
}
Class loading
When a program wants to use a class , If the class has not been loaded into memory , Then the system will go through Class loading , Class connection , Class initialization These three steps are used to initialize the class .
In general ,JVM These three steps will be completed in succession , So sometimes these three steps are collectively referred to as class loading .
Class loading :JVM Take bytecode from different data sources (class file ,jar package , Network, etc. ) Convert to binary byte stream to load into memory , And generate Class Instance object .
Class connection
Validation phase : Make sure .class The byte stream of the file contains information that meets the requirements of the current virtual machine , Does not harm the security of virtual machine itself .
Preparation stage : by static Decorated field variables allocate memory and set default initial values , Not included final Embellished static, because final It will be allocated at compile time .
Analytic stage : It mainly replaces the symbolic reference in the constant pool with a direct reference .
Class initialization : Last stage of class loading , Actually start executing what's defined in the class Java Program code , This stage is the implementation of < clinit >() Method process .
< clinit >() Method is created by the compiler in the order in which statements appear in the source file , Automatically collect the assignment actions of all static variables in the class and the statements in the static code block in turn , And merge .
Virtual opportunity guarantees a class of < clinit >() Methods are properly locked in a multithreaded environment , Sync , If multiple threads are initializing a class at the same time , There will only be one thread to execute this class < clinit >() Method , All other threads need to block and wait , Until the active thread executes < clinit >() Methods to complete .
If this class has a superclass , Then initialize it , Perform static initializer and static initialization member variables .

@SuppressWarnings({
"all"})
public class lambdademo {
public static void main(String[] args) {
System.out.println(fun.num);
}
}
/** * stay Linking Of Preparation Stage , Yes num Allocate memory , Initialize to 0 * stay Initialization Stage , collect Static variables , Static code block to <clinit> In the method , And implement <clinit> Method */
class fun {
static{
System.out.println(" Static code blocks are executed ");
num = 300;
}
static int num = 100;
public fun(){
System.out.println(" The constructor is executed ");
}
}
// Output
Static code blocks are executed
100
// The results of the analysis , It is obvious that , What is done in class loading , Of course, we didn't create objects , So the constructor is not called
// The general process should be like this
1. load fun class , And generate a corresponding Class example , And in the method area Bytecode binary data
2. Linking Stage , by num Allocate memory , Initialize to 0
3. Initialization Stage , In the order it appears in the source file , Collect the assignment actions of all static variables and the statements in the static code block in turn , Merge to <clinit> In the method , And implement .
clinit() {
/// Statements in static code blocks /
System.out.println(" Static code blocks are executed ");
num = 300;
/// Static variable assignment statement //
num = 100;
}
Field Some other of the class API
getModifiers(): default/0 , public/1 , private/2 , protected/4 , static/8 , final/16
// have access to Modifier.toString(cls.getModifiers()) Convert a number to a string
getType(): Return to one Class object , Represents the type of the property
getName(): Return property name
Class<fun> funClass = fun.class;
Field[] fields = funClass.getDeclaredFields();
for(Field f : fields){
System.out.println(f.getModifiers()); // The returned value represents its access modifier
System.out.println(f.getType()); // int/double/java.lang.String ...
System.out.println(f.getName()); // Property name
}
Mehod class
getModifiers() // Access modifier
getReturnType() // return Class object , Represents the return type
getName() // Method name
getParameterTypes() // return Class[], Represents an array of parameter types
Create objects by reflection
Class<?> cls = Class.forName("com.itheima.fun");
// 1. Using a parameterless constructor
Object o1 = cls.newInstance();
// 2. Through a parametric constructor ( Specify the parameter list )
Constructor<?> cons1 = cls.getDeclaredConstructor(String.class);
Object o2 = cons1.newInstance("xxx");
// 3. You can also use private Constructor
Constructor<?> cons2 = cls.getDeclaredConstructor(int.class, String.class);
cons2.setAccessible(true);
Object o3 = cons2.newInstance(100, "fang_shou_ba..");
Class Objects are generated as follows :
1、 Class name .class
JVM Class loader will be used , Load classes into memory , Do not do class initialization , return Class The object of .
2、Class.forName(“ The fully qualified name of the class ”)
Load class , And do class initialization ( Will execute static code blocks and initialize static variables ), return Class The object of .
Usually use new When you create an object , The class will be loaded first , After performing Non static code block , Then execute the constructor .
Several generation Class The difference between instance methods
边栏推荐
- 7天零基础能考证HCIA吗?华为认证系统学习路线分享
- After the promotion, sales volume and flow are both. Is it really easy to relax?
- 2018 Jiangsu Vocational College skills competition vocational group "information security management and evaluation" competition assignment
- Sqlserver multithreaded query problem
- $refs:组件中获取元素对象或者子组件实例:
- 使用net core优势/为什么使用
- Initial experience of addresssanitizer Technology
- Multithreading and high concurrency (9) -- other synchronization components of AQS (semaphore, reentrantreadwritelock, exchanger)
- 非父子组件的通信
- 品牌·咨询标准化
猜你喜欢
![How to model and simulate the target robot [mathematical / control significance]](/img/bd/79f6338751b6773859435c54430ec3.png)
How to model and simulate the target robot [mathematical / control significance]

品牌·咨询标准化

unity3d学习笔记

Network foundation - header, encapsulation and unpacking

从零到一,教你搭建「CLIP 以文搜图」搜索服务(二):5 分钟实现原型

大促过后,销量与流量兼具,是否真的高枕无忧?

Several index utilization of joint index ABC

联合索引ABC的几种索引利用情况

Answer to the second stage of the assignment of "information security management and evaluation" of the higher vocational group of the 2018 Jiangsu Vocational College skills competition

2018年江苏省职业院校技能大赛高职组“信息安全管理与评估”赛项任务书
随机推荐
After the promotion, sales volume and flow are both. Is it really easy to relax?
Under what circumstances should we consider sub database and sub table
Stack and queue-p79-10 [2014 unified examination real question]
From zero to one, I will teach you to build the "clip search by text" search service (2): 5 minutes to realize the prototype
Anr principle and Practice
Leetcode T1165: 日志分析
Matlab tips (29) polynomial fitting plotfit
[explanation of JDBC and internal classes]
How to do sports training in venues?
组件的通信
品牌电商如何逆势增长?在这里预见未来!
Please ask a question, flick Oracle CDC, read a table without update operation, and repeatedly read the full amount of data every ten seconds
什么情况下考虑分库分表
How can brand e-commerce grow against the trend? See the future here!
AddressSanitizer 技术初体验
IP address
非父子组件的通信
从零到一,教你搭建「CLIP 以文搜图」搜索服务(二):5 分钟实现原型
MySQL binlog related commands
jdbc数据库连接池使用问题