当前位置:网站首页>How to create a static object variable of its own class?
How to create a static object variable of its own class?
2022-07-26 20:47:00 【Charles bug Mixc】
Preface
C: In the past two weeks, I have been frantically interviewing and recruiting the project team , Last night, 10 Some more , The product director sent a question in the interview group , What is the running result , The title is as follows :
class Singleton {
private static Singleton singleton = new Singleton();
public static int count1;
public static int count2 = 3;
private Singleton() {
count1++;
count2++;
}
public static Singleton getInstance() {
return singleton;
}
}
public class Test {
public static void main(String[] args) {
Singleton singleTon = Singleton.getInstance();
System.out.println("count1=" + singleTon.count1);
System.out.println("count2=" + singleTon.count2);
}
}
This aroused our enthusiasm for doing Technology , Then analyze it .
Simple analysis
1、 After a brief look at the topic , This is not a singleton class that adopts the hungry Han singleton pattern , Next, of course, is to find the program entry .
2、 stay Test Class main In the method , First, I call Singleton Class getInstance() Method , Obviously, this is to get Singleton The only object of this singleton class ( example ) 了 .
3、 Then get the unique object ( example ) after , Output Singleton Two static member variables of class count1、count2 Value .( Although calling static information by object name is not recommended , But it has no effect on the results )
4、 See here , There are no other output statements in the two classes , So the final result is to see count1、count2 Output value of .
5、 The key is coming. : Calling getInstance() Before the method , because Singleton Class not loaded , So you must load the class first , because count1、count2、Singleton The only object of ( example ) It's all static , So they will be loaded as the class is loaded . among int Type of count1 The variable does not specify an initial value , The default is 0,count2 The initial value specified is 3, Singleton Class ( example ) To create a constructor that will call , The construction method is also right count1 and count2 It's self increasing 1 Arithmetic , The result is naturally count1 yes 1,count2 yes 4.
After such a spark and lightning analysis , Confidently sent the answer to the Group .
count1=1
count2=4
In-depth analysis of
Obviously wrong , Otherwise, it will not be recorded separately . The reason for the wrong answer , Because the loading order of static information is ignored , The loading order of static information is determined by the coding order , The preconceived ones in the above analysis count1 and count2 Finished loading , But in fact, the first implementation is Singleton The only object of ( example ) Create and assign variables , Then there is implementation count1、count2.
We can go through javap -c Singleton.class Disassemble the bytecode file , After anti exchange compilation JVM The instructions are as follows :
Compiled from "Test.java"
class org.example.Singleton {
public static int count1;
public static int count2;
public static org.example.Singleton getInstance();
Code:
// obtain singleton Static object variables , And push its value to the top of the stack
0: getstatic #4 // Field singleton:Lorg/example/Singleton;
// Return from current method singleton Object reference
3: areturn
static {
};
Code:
// 1、 establish Singleton Class object , And assign it to the static object variable singleton
// 1.1 Create objects
0: new #5 // class org/example/Singleton
// 1.2 Copy the stack top value and push the copied value into the stack top
3: dup
// 1.3 call Singleton Class constructor ,count1 and count2 Self increasing 1, here count1 by 1,count2 by 1
4: invokespecial #6 // Method "<init>":()V
// 1.4 The object is created successfully, and the object reference is assigned to the static object variable singleton
7: putstatic #4 // Field singleTon:Lorg/example/Singleton;
// 2、 take 3 Assign a value to count2
// 2.1 take int type 3 Push to top of stack
10: iconst_3
// 2.2 by count2 Static variable assignment
11: putstatic #3 // Field count2:I
// 3、 The ending method
14: return
}
Obviously ,count2 Finally, it is assigned 3 了 .
The correct answer is :
count1=1
count2=3
Extra extension
What if you really want to get the previous results ?
count1=1
count2=4
Only need to count1、count2 The order of the two static variables is adjusted to Singleton Class ( example ) Just above the variable .
class Singleton {
public static int count1;
public static int count2 = 3;
private static Singleton singleton = new Singleton();
private Singleton() {
count1++;
count2++;
}
public static Singleton getInstance() {
return singleton;
}
}
public class Test {
public static void main(String[] args) {
Singleton singleTon = Singleton.getInstance();
System.out.println("count1=" + singleTon.count1);
System.out.println("count2=" + singleTon.count2);
}
}
We pass... Again javap -c Singleton.class Disassemble the bytecode file , After anti exchange compilation JVM The instructions are as follows :
Compiled from "Test.java"
class org.example.Singleton {
public static int count1;
public static int count2;
public static org.example.Singleton getInstance();
Code:
// obtain singleton Static object variables , And push its value to the top of the stack
0: getstatic #4 // Field singleton:Lorg/example/Singleton;
// Return from current method singleton Object reference
3: areturn
static {
};
Code:
// 1、 take 3 Assign a value to count2,count2 This is the case 3
// 1.1 take int type 3 Push to top of stack
0: iconst_3
// 1.2 by count2 Static variable assignment
1: putstatic #3 // Field count2:I
// 2、 establish Singleton Class object , And assign it to the static object variable singleton
// 2.1 Create objects
4: new #5 // class org/example/Singleton
// 2.2 Copy the stack top value and push the copied value into the stack top
7: dup
// 2.3 call Singleton Class constructor ,count1 and count2 Self increasing 1,count1 This is the case 1,count2 This is the case 4
8: invokespecial #6 // Method "<init>":()V
// 2.4 The object is created successfully, and the object reference is assigned to the static object variable singleton
11: putstatic #4 // Field singleTon:Lorg/example/Singleton;
// 3、 The ending method
14: return
}
Obviously ,count2 Finally, it was increased to 4 了 .
边栏推荐
- 李彦宏遭“泼冷水”热情不减!百度结盟华为麒麟,发布“鸿鹄”芯片
- Auto. JS rotation Icon
- Face recognition and fingerprint recognition are weak? Pentagon develops long-distance heartbeat recognition
- Shell综合应用案例,归档文件
- Correct the classpath of your application so that it contains compatible versions of the classes com
- Leetcode刷题之——链表总结
- YGG cooperates with my pet hooligan, AMGI's flagship NFT project, to enter the rabbit hole
- nmap安装和使用
- [Delphi] different platform descriptions of borderstyles of FMX form
- The sandbox cooperates with artist Alec monopoly
猜你喜欢

Easycvr device management list page, paging data does not display problem repair

Easy gene | introduction to macrovirus sequencing technology

Pandonia spirit voxedit creation competition

连接池快速入门

CentOS7关于Oracle RAC 11GR2部署磁盘分区问题
![Chapter 2: encounter obstacles! Bypass WAF filtering! [SQL injection attack]](/img/f8/e6991852547a370f4363a2b763e52e.png)
Chapter 2: encounter obstacles! Bypass WAF filtering! [SQL injection attack]

Experiment 5 OSPF comprehensive experiment

BGP的基本配置和聚合

查询字段较多时可以添加普通查询和高级查询两种情况

易基因|宏病毒组测序技术介绍
随机推荐
The sandbox cooperates with artist Alec monopoly
Software testing - development test content specification (project test template)
【Delphi】FMX Form的BorderStyles不同平台说明
实验5 OSPF综合实验
Gbase learning - install gbase 8A MPP cluster v95
Basic configuration and aggregation of BGP
深度可分离卷积(DepthwiseSeparableConvolution):Depthwise卷积与Pointwise卷积
884. 两句话中的不常见单词-哈希表
serializable接口的作用是什么?
A super simple neural network code with 5 coordinates for one layer node training
【微信小程序】零基础学 | 小程序语法
Can the training software test be employed
Sword finger offer46 translates numbers into strings
Easy gene | introduction to macrovirus sequencing technology
twenty million two hundred and twenty thousand seven hundred and twenty-six
Kotlin - coroutinecontext
BUU刷题记4
Establishment of APP automation testing framework (VIII) -- establishment of ATX server2 multi device cluster environment
MPLS 多协议标签交换技术
BGP--边界网关协议