当前位置:网站首页>Anonymous inner classes and local variables
Anonymous inner classes and local variables
2022-06-09 12:04:00 【howeres】
Anonymous inner class And local variable
An anonymous class Cannot access... In an external class method local variable , Unless the variable is declared as final type ;
Usually in a method , There are local variables and temporary anonymous classes , When using :
Integer i = 8848;
new Thread(
() -> {
Integer j = i; // Report errors i Can't use
System.out.println("j = " + j);
})
.start();
i = 996;
So unless the declared variable i by final ( Or it will not be used later , The compiler will automatically convert to final), Otherwise, you can't operation local variable i .
It's actually the object of the inner class that uses it , It can be called in the life cycle of an inner class object , When an inner class attempts to access a local variable in an outer method , The local variables of the external method probably no longer exist , Then we have to extend its life , Copy to inner class , And copying can lead to inconsistencies , So we need to use final Declaration of conformity .
here , The internal class will automatically copy the external variables References to , for fear of : The reference values obtained by the inner class are inconsistent 、 Internal class modification reference , The parameter values of external methods are inconsistent before and after modification .
If it is a member variable of an external class, it does not need to be final Of , Because the inner class itself will contain a reference to the outer class ( External class .this), Therefore, when callback, you must be able to access .
Anonymous inner class And Member variables
- Member variables , Through the constructor of anonymous class , Copy the address reference of an instance , To call the instance properties ( The attribute is private It's OK ), It ensures that when the variable changes Consistency of data references , Don't have to add final;
- Global variables are the same (static), In anonymous inner classes , Variables can be accessed directly through classes , Sure Ensure the consistency of variable references , So don't add final;
Anonymous inner class definition
- Anonymous inner class : In class Member method Inside , Simultaneous completion Definition and Instantiation Class . Have grammar sugar , The compiler helps create classes , This anonymous name already has a name after compilation , The class name generated by this compilation , To create an object , It is the same as the normal process of implementing classes .
ch.pipeline()
.addLast(
new ChannelDuplexHandler() {
// Handle Other than reading and writing Special events
@Override
public void userEventTriggered(
ChannelHandlerContext ctx, Object evt) throws Exception {
IdleStateEvent event = (IdleStateEvent) evt;
// whether Read timeout
if (event.state() == IdleState.WRITER_IDLE) {
ctx.writeAndFlush(new PingMessage());
}
}
});
// Or something like this
return ()-> {
};
reason : Difficulties in compiler implementation , Of the inner class object Life cycle Will surpass local variable Life cycle of .
- The life cycle of a local variable : When the method is called , The local variables in this method are created in the stack , When the method call ends , Backstack , All of these local variables died .
- The inner class object life cycle is the same as other classes : Create an anonymous inner class object , The system allocates memory for this object , Until no reference variable points to the memory allocated to the object , It will die ( By JVM Garbage collection ).
So one situation that is entirely possible is : Member method call ended , The local variable is dead , But objects of anonymous inner classes are still alive . If an object of an anonymous inner class accesses a local variable in the same method , It requires that as long as the anonymous inner class object is alive , Then the local variables in the stack that it wants to access cannot “ Death ”.
The process
Anonymous inner class objects accessing the same method are defined as final Type of local variable . Defined as final after , Implementation method of compiler : For all anonymous inner class objects to access final Type local variables , Are copied as a data member of the object . such , Even in the stack The local variable is dead , But it is defined as final The value of a local variable of type never changes , Therefore, the anonymous inner class object after the local variable dies , You can still access final Type of local variable , Because it itself Made a copy of , And it is always consistent with the value of the original local variable .
边栏推荐
- Resttemplate usage details and pit stepping records
- 2021年下半年系统集成项目管理工程师案例分析真题及答案解析
- Preparation guide for 2022 soft test information security engineer examination
- 6. exchange the nodes in the linked list in pairs
- 10 | summary: summary of middle platform landing tool resources
- Range方法返回对象转换办法
- 8K resolution 7680*4320
- Tag greedy - brush questions to prepare knowledge - greedy problem solving methods + lt.455 Distribute cookies + lt.376 Wobble sequence
- Open IPv6 access on the website to test whether it supports IPv6
- Go zero micro Service Practice Series (II. Service splitting)
猜你喜欢

04 | everything must be done in advance: four issues that must be clearly considered before the construction of China Taiwan Relations

HEVC之HM学习02

LR11安装报错:此计算机上缺少vc2005_sp1_with_atl_fix_redist,请安装所有缺少的必要组件,然后重新运行此安装。

05 | D4 model: overview of China Taiwan planning and construction methodology

ThreadPoolExecutor 从精通到入门

03 | definition of China Taiwan: what are we talking about when we talk about China Taiwan?

死锁的排查工具有哪些?
![[patch analysis] cve-2016-8610: patch analysis of](/img/cb/77578a38c2c907c6ee83ac0f70df88.png)
[patch analysis] cve-2016-8610: patch analysis of "SSL death alert" vulnerability leading to denial of service

JMeter安装教程

6. < tag backtracking and cutting problems > lt.131 Split palindrome string
随机推荐
01 | context: why is Zhongtai so popular?
[signalr complete series] Realization of signalr real-time communication in net core
15 Win32 class library name in WMI
win10你的组织已关闭自动更新问题怎么解决?
H3C Certified Safety Technology Senior Engineer
【数据中台】00丨开篇词丨数据中台,是陷阱?还是金钥匙?
7.<tag-回溯和子集问题>lt.70.子集 + lt.90.子集 II
09 | the fourth step: the construction and delivery of the middle office
Win11 officially released new features
JMeter安装教程
9. lt.491 Longest increasing subsequence
Dotnet core can also coordinate distributed transactions!
11.<tag-二叉树和BST基础>lt.501. 二叉搜索树中的众数
xxl-job 使用初体验
8. < tag backtracking and full arrangement > lt.46 Full Permutation + lt.47 Full arrangement II
12.<tag-二叉树和BST基础>lt.701. 二叉搜索树中的插入操作 dbc
传入base64集合,导出大图片
What is the difference between a fire engineer and a fireman?
04 | everything must be done in advance: four issues that must be clearly considered before the construction of China Taiwan Relations
Win11正式发布新功能