Java 17 Recipes


-7. Accessing Class Variables from a Lambda


Download 3.2 Mb.
Pdf ko'rish
bet123/245
Sana02.06.2024
Hajmi3.2 Mb.
#1839910
1   ...   119   120   121   122   123   124   125   126   ...   245
Bog'liq
Java 17 Recipes

6-7. Accessing Class Variables from a Lambda
Expression
 Problem
The class you are writing contains instance variables, and you want to make them 
available for use via a lambda expression within the class.
 Solution
Use instance variables contained in enclosing classes, as needed, from within lambda 
expressions. In the following class, the lambda expression contained within the 
VariableAccessInner.InnerClass.lambdaInMethod() method can access all enclosing 
class instance variables. Thus, it can print the VariableAccessInner CLASSA variable, 
if needed.
public class VariableAccessInner {
public String CLASSA = "Class-level A";
class InnerClass {
public String CLASSA = "Class-level B";
void lambdaInMethod(String passedIn) {
String METHODA = "Method-level A";
Consumer l1 = x -> {
System.out.println(x);
System.out.println("CLASSA Value: " + CLASSA);
System.out.println("METHODA Value: " + METHODA);
};
l1.accept(CLASSA);
l1.accept(passedIn);
}
}
}
ChapTer 6 LaMbda expressIons


228
Now, let’s execute lambdaInMethod using the following code.
VariableAccessInner vai = new VariableAccessInner();
VariableAccessInner.InnerClass inner = vai.new InnerClass();
inner.lambdaInMethod("Hello");
The main class is as follows.
public class MainClass {
public static void main(String[] args){
System.out.println("==VariableAccessInner==");
VariableAccessInner vai = new VariableAccessInner();
VariableAccessInner.InnerClass inner = vai.new InnerClass();
inner.lambdaInMethod("Hello");
}
}
The following is the result.
==VariableAccessInner==
Class-level B
CLASSA Value: Class-level B
METHODA Value: Method-level A
Hello
CLASSA Value: Class-level B
METHODA Value: Method-level A
Note The 
CLASSA variable is overridden by a variable using the same identifier 
within the InnerClass class. Therefore, the CLASSA instance variable that 
belongs to VariableAccessInner is not printed within the lambda expression.
ChapTer 6 LaMbda expressIons


229

Download 3.2 Mb.

Do'stlaringiz bilan baham:
1   ...   119   120   121   122   123   124   125   126   ...   245




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling