当前位置:网站首页>Reflection, enumeration, and lambda expressions
Reflection, enumeration, and lambda expressions
2022-07-26 15:39:00 【Come to the pot】
Catalog
2.1 Class Related methods in class
2.3 Advantages and disadvantages of reflection
4. Enumerations cannot be reflected
5.3 Lambda The basic use of expressions
5.5 Lambda Use... In a collection
5.6 Lambda Advantages and disadvantages of expressions
1. Reflexive understanding
(1) The reflex mechanism (reflection)
java The reflection mechanism is In operation , For any class , Can know all the properties and methods of this class ; For any object , Can call any of its methods and properties , Now that you can get , Then you can modify some type information ; such The function of dynamically obtaining information and dynamically calling methods is called java The reflexive mechanism of language
(2) application
1. The most important role of reflection is to develop various general frameworks
2. In the daily process of third-party application development , Often encounter a member variable of a class 、 Methods are either private or developed only for system applications , It can be used at this time java Reflection mechanism obtains private members or methods
(3) Reflection basic information
java Many objects in a program run in two types :
Runtime type and compile time type
The essence of program running is to find the real information of the object's class at run time , Through the reflection mechanism, you can determine which classes the object and class belong to
2. Reflection related classes
| Class name | purpose |
|---|---|
| Class class | Entity representing class , Running java The interface that represents a class in an application |
| Field class | Member variables representing the class / Attributes of a class |
| Method class | Method representing class |
| Constructor class | Represents the construction method of a class |
2.1 Class Related methods in class

(1) Commonly used methods to obtain class related information
| Method | purpose |
|---|---|
| getClassLoader() | Get the class loader |
| getDeclaredClasses() | Returns an array , Array contains objects of all classes and interface classes in this class ( Including private ownership ) |
| forName(String className) | Returns the object of the class according to the class name |
| newInstance() | Create an instance of a class |
| getName() | Get the full pathname of the class |
(2) Commonly used methods to obtain properties in classes ( The return value is Field relevant )
| Method | purpose |
|---|---|
| getField(String name) | Get a public property object |
| getFields() | Get all public property objects |
| getDeclaredField(String name) | Get a property object |
| getDeclaredFields() | Get all property objects |
(3) Get constructor related methods in the class ( The return value is Constructor relevant )
| Method | purpose |
|---|---|
| getConstructor(Class...<?>parameter Types) | Get the public constructor matching the parameter type in this class |
getConstructors() | Get all the public constructors of this class |
getDeclaredConstructor(Class...<?> parameterTypes) | Get the constructor matching the parameter type in this class |
getDeclaredConstructors() | Get all the construction methods of this class |
(4) Get the method in the class Related methods ( The return value is Method relevant )
| Method | purpose |
|---|---|
getMethod(String name, Class...<?> parameterTypes) | Get a public method of this class |
getMethods() | Get all the public methods of this class |
getDeclaredMethod(String name, Class...<?> parameterTypes) | Get a method of this class |
getDeclaredMethods() | Get all the methods of this class |
2.2 Reflex use
(1) get Class Three ways of objects
1. Use Class.forName(" The full pathname of the class "); Static methods
public static void main(String[] args) throws ClassNotFoundException { //1. adopt Class Object's forName() Static method acquisition ( Most used , Pay attention to the exception ) Class<?> c1 = Class.forName("reflectdemo.Student"); }2. Use .class Method
//3. Directly through type .class obtain ( More secure , Higher program performance ) Class<?> c3 = Student.class;3. Using the getClass() Method
//2. adopt getClass obtain class object Student student = new Student(); Class<?> c2 = student.getClass();
(2) Use of reflection
All reflection related packages are in import.java.lang.reflect It's a bag
1. Create objects by reflection
public static void reflectNewInstance() {
try {
Class<?> c1 = Class.forName("reflectdemo.Student");
Student student = (Student) c1.newInstance();
System.out.println(student);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}2. Reflection private construction method , The shielding content is to obtain the public construction method
public static void reflectPrivateConstructor() {
try {
Class<?> c1 = Class.forName("reflectdemo.Student");
// Note that the corresponding parameters are passed in
Constructor<?> constructor =
c1.getDeclaredConstructor(String.class, int.class);
// Are you sure you want to access private methods outside the class . Set to true Access rights can be modified after
constructor.setAccessible(true);
Student student = (Student) constructor.newInstance("xiangyu",22);
System.out.println(student);
} catch (ClassNotFoundException e) {
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}3. Reflect private properties
public static void reflectPrivateField() {
try {
Class<?> c1 = Class.forName("reflectdemo.Student");
Student student = (Student) c1.newInstance();
// You can modify the value of this property
Field field = c1.getDeclaredField("name");
// Access private , Ask in advance whether you are sure to visit
field.setAccessible(true);
field.set(student,"liubang");
System.out.println(student);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
}4. Reflect private methods
public static void reflectPrivateMethod() {
try {
Class<?> c1 = Class.forName("reflectdemo.Student");
Student student = (Student) c1.newInstance();
Method method = c1.getDeclaredMethod("function", String.class);
method.setAccessible(true);
method.invoke(student," Pass parameters to you through reflection ");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}2.3 Advantages and disadvantages of reflection
advantage :
1. Any class , Can know all the properties and methods of this class
Any object , Can call any of its methods
2. Increase the flexibility and scalability of the program , Reduce coupling , Improve self adaptability
3. Reflection is used in many frameworks
shortcoming :
1. Reflection because many methods are called , There will be the problem of efficiency reduction
2. Reflection technology bypasses the technology of source code , There will be maintenance problems , And reflection code is more complex than the corresponding direct code
3. Use of enumeration
(1) Enumeration understanding
Enumeration is in JDK1.5 Introduced
effect : Organize a set of constants , Before that, it represents a set of constants by using the method of defining constants
The essence : yes java.lang.Enum Subclasses of , That is, the custom enumeration class , It just doesn't show inheritance Enum, It also inherits this class by default
public enum enumDemo01 {
ONE,TWE,TREE;// enumerable object
}(2)switch sentence
public static void main1(String[] args) {
enumDemo01 enumDemo01 = enumdemo.enumDemo01.TWE;
switch (enumDemo01) {
case ONE:
System.out.println("1");
break;
case TWE:
System.out.println("2");
break;
case TREE:
System.out.println("3");
break;
default:
break;
}
}
(3)Enum Common methods of class
| Method name | describe |
|---|---|
| values() | Returns all members of an enumeration type as an array |
| ordinal() | Get the index position of enumeration member |
| valueOf() | Convert a normal string to an enumeration instance |
| compareTo() | Compare the order in which two enumeration members are defined |
public static void main2(String[] args) {
enumDemo01[] enumDemo01s = enumDemo01.values();
for (int i = 0; i < enumDemo01s.length; i++) {
System.out.println(enumDemo01s[i] + " Serial number :" + enumDemo01s[i].ordinal());
}
enumDemo01 e1 = enumDemo01.valueOf("TREE");
System.out.println(e1);
}public static void main(String[] args) {
// Get enumerated instances TWE
enumDemo01 e1 = enumDemo01.TWE;
// Get enumerated instances TREE
enumDemo01 e2 = enumDemo01.TREE;
// The comparison is the serial number
System.out.println(enumDemo01.TREE.compareTo(e1));
System.out.println(ONE.compareTo(TWE));
System.out.println(ONE.compareTo(TREE));
}(4) The construction method of enumeration is private by default
public enum enumDemo01 {
ONE,TWE("twe",2),TREE;// enumerable object
public String figure;
public int ordinal;
// The construction method of enumeration is private by default
enumDemo01(String figure, int ordinal) {
this.figure = figure;
this.ordinal = ordinal;
}
enumDemo01() {
}
}(5) Enumerate the advantages and disadvantages
advantage :
1. Enumerating constants is simpler and safer
2. Enumeration has built-in methods , Code and beauty
3. Enumerations cannot be reflected and serialized
shortcoming :
1. Non inheritable , Can't expand
4. Enumerations cannot be reflected
I learned reflection before , For any class , Even if the constructor is private , You can also get the instance object through reflection , Then the construction method of enumeration is also private , Can you get it through reflection ?
public class Demo01 {
public static void reflectPrivateConstructor() throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
Class<?> c1 = Class.forName("enumdemo.enumDemo01");
Constructor<?> constructor =
c1.getDeclaredConstructor(String.class, int.class,String.class, int.class);
constructor.setAccessible(true);
enumDemo01 e1 = (enumDemo01)constructor.newInstance("xigua",66);
System.out.println(e1);
}
public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
reflectPrivateConstructor();
}
}
You can see that it is wrong , find newInstance Source code
You can see

Enumerations cannot be reflected . So enumeration is very safe
5. Lambda expression
5.1 Lambda Expression syntax
(1) understand
Lambda Expressions are equivalent to anonymous functions ,Lambda Expressions allow one function to be used as an argument to another function ;
Lambda Expressions allow you to use expressions instead of functional interfaces ;
Lambda Expressions are just like methods , Provide a list of normal parameters and the body using these parameters ( It could be an expression 、 Code block )
lambda Expressions can also be called closures
(2) grammar
grammar :(parameters)-> expression or (parameters) -> {statements;}
Lambda The expression consists of three parts :
1) paraments: amount to Method , The parameters here are functions in the functional interface
Parameter types can be explicitly declared , You can also jvm Implicit judgment
Parentheses can be omitted when there is only one inferred type
2)->: amount to “ Be used for ”
3) Method body : The expression can be Code block , It can also be Implementation of methods in functional interfaces
You can have a return value , You can also not go back
//1. No parameters required , Direct return value
()-> 6
//2. A parameter type , Return value
x -> 2*x
//3. Two parameters , Return value
(x,y) -> x+y
//4. Two int Type integer , Return value
(int x,int y) -> x*y
//5. Receive one string object , Print on console , No return value
(String s) -> system.out.print(s)5.2 Functional interface
Functional interface definition : An interface has and has only one abstract method .
When we write functional interfaces, we can declare @FunctionalInterface annotation , In this way, the compiler can request the functional interface according to its definition , At this point, if there are two abstract methods , The compiler will report an error

public class Demo01 {
public static void main(String[] args) {
PriorityQueue<Integer> priorityQueue = new PriorityQueue<>(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o2-o1;
}
});
}
// At this point, it is equivalent to a class implementation Comparator Interface At the same time, the abstract method is rewritten compare
PriorityQueue<Integer> priorityQueue = new PriorityQueue<>((o1, o2) -> {return o2-o1;});
PriorityQueue<Integer> priorityQueue1 = new PriorityQueue<>(((o1, o2) -> o2-o1));
}
5.3 Lambda The basic use of expressions
Lambda Expression is essentially an anonymous functionIt can be understood as :Lambda Is the simplification of anonymous inner classesIn fact, it creates a class , Implement the interface , Overriding interface methods
Let's write a few interfaces , Use them separately Lambda Expressions and do not apply Lambda Expression to call comparison
(1) No return value no parameter
@FunctionalInterface
interface NoParameterNoReturn {
void test();
}The two methods call comparison respectively
public static void main(String[] args) {
NoParameterNoReturn noParameterNoReturn = new NoParameterNoReturn() {
@Override
public void test() {
System.out.println(" Test it ");
}
};
noParameterNoReturn.test();
NoParameterNoReturn noParameterNoReturn1 = () -> {System.out.println(" Test it ");};
NoParameterNoReturn noParameterNoReturn2 = () -> System.out.println(" Test it ");
NoParameterNoReturn noParameterNoReturn3 = () -> {
System.out.println(" test 1 Next ");
System.out.println(" test 2 Next ");
};
}(2) No return value a parameter
@FunctionalInterface
interface OneParameterNoReturn {
void test(int a);
} public static void main(String[] args) {
OneParameterNoReturn oneParameterNoReturn = (int x) -> {
System.out.println(x);
};
oneParameterNoReturn.test(100);
System.out.println(" simplify :");
OneParameterNoReturn oneParameterNoReturn1 = x -> System.out.println(x);
OneParameterNoReturn oneParameterNoReturn2 = System.out::println;
oneParameterNoReturn1.test(10);
}(3) No return value multiple parameters
@FunctionalInterface
interface MoreParameterNoReturn {
void test(int a,int b);
} public static void main(String[] args) {
MoreParameterNoReturn moreParameterNoReturn = (int a,int b) -> {
System.out.println(a+b);
};
moreParameterNoReturn.test(10,20);
// Both types are required to be omitted
MoreParameterNoReturn moreParameterNoReturn1 = (a,b) -> System.out.println(a+b);
moreParameterNoReturn1.test(20,30);
}(4) With return value and no parameter
@FunctionalInterface
interface NoParameterReturn {
int test();
} public static void main(String[] args) {
NoParameterReturn noParameterReturn = () -> {return 10;};
int ret = noParameterReturn.test();
System.out.println(ret);
NoParameterReturn noParameterReturn1 = () ->10;
int ret2 = noParameterReturn1.test();
System.out.println(ret2);
}(5) There is a parameter with a return value
@FunctionalInterface
interface OneParameterReturn {
int test(int a);
} public static void main(String[] args) {
OneParameterReturn oneParameterReturn = x -> 2*x;
System.out.println(oneParameterReturn.test(10));
}(6) Multiple parameters with return value
@FunctionalInterface
interface MoreParameterReturn {
int test(int a,int b);
} public static void main(String[] args) {
MoreParameterReturn moreParameterReturn = (x,y) -> x+y;
System.out.println(moreParameterReturn.test(10, 20));
}Lambda Grammatical rules :1. Parameter types can be omitted , And if you want to omit, you should omit all2. When there is only one parameter in the parentheses of parameters , Brackets can be omitted3. If there is only one line of code in the method body , Then the braces can be omitted4. If there is only one line of code in the method body , In especial return sentence , So braces and return Keywords can be omitted
5.4 Variable capture
(1) Anonymous internal class variables capture
class Demo {
void fun() {
System.out.println("dasd");
}
}In anonymous inner classes , Variable capture refers to the capture of external variables
External variables are used in anonymous inner classes , It must be unmodified in the anonymous inner class
Internal variables do not affect
public static void main7(String[] args) {
int a = 10;
// In anonymous inner classes , Variable capture ( Capture of external variables ), The external variables used must be unmodified
new Demo() {
@Override
void fun() {
int c = 99;
c = 100;
System.out.println(c+" Rewrite " + a);
}
}.fun();
}(2)Lambda Variable capture
Lambda There are variables in the expression , Must understand Lambda After variable capture , Can understand Lambda The scope of the expression , Its variable capture rules are similar to anonymous inner class rules
5.5 Lambda Use... In a collection
Some interfaces are added to the set , Convenient and convenient Lambda Expression docking
Here are some examples
(1)Collection Interface forEach() Print all
(2)List Interface sort() Sort
Write and use Lambda Expressions and unused methods
public static void main(String[] args) {
//Lambda The interior is also an anonymous inner class , External variables cannot be modified
ArrayList<String> list = new ArrayList<>();
list.add("Hello");
list.add("bit");
list.add("hellol");
list.add("lambda");
// Print all
list.forEach(new Consumer<String>() {
@Override
public void accept(String s) {
System.out.println(s);
}
});
list.forEach(s -> System.out.println(s));
// Sort
list.sort(new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o1.compareTo(o2);
}
});
list.sort(((o1, o2) -> o1.compareTo(o2)));
list.forEach(s -> System.out.println(s));
}(3)Map Interface forEach()
public static void main(String[] args) {
HashMap<Integer, String> map = new HashMap<>();
map.put(1, "hello");
map.put(2, "bit");
map.put(3, "hello");
map.put(4, "lambda");
map.forEach(new BiConsumer<Integer, String>() {
@Override
public void accept(Integer integer, String s) {
System.out.println("key:"+integer+"val:"+s);
}
});
map.forEach((x,y)-> System.out.println("key:"+x+"val:"+y));
}5.6 Lambda Advantages and disadvantages of expressions
advantage :
1. Code Introduction , Rapid development
2. The convenient function becomes
3. Improve collection operations
shortcoming :
1. Poor code readability
2. Not easy to debug
3. In non parallel computing , Many calculations are not necessarily traditional for High performance
边栏推荐
- Glyphs V3 Font Icon query
- 【C】 Flexible array
- How much help does solid state disk have for game operation
- 04 callable and common auxiliary classes
- Digital warehouse: iqiyi digital warehouse platform construction practice
- Creation and traversal of binary tree
- FOC电机控制基础
- Pytorch installation CUDA corresponding
- Desktop application layout
- [static code quality analysis tool] Shanghai daoning brings you sonarource/sonarqube download, trial and tutorial
猜你喜欢

Practical purchasing skills, purchasing methods of five bottleneck materials

pytorch安装 CUDA对应
![[leetcode daily question] - 268. Missing numbers](/img/96/dcf18522257dea7cb7e52f5bb7ced3.png)
[leetcode daily question] - 268. Missing numbers

gcc/g++与动静库以及gdb

【基础】动态链接库/静态链接库的区别

【EXPDP导出数据】expdp导出23行记录,且不包含lob字段的表,居然用时48分钟,请大家帮忙看看

Glyphs V3 Font Icon query

anaconda No module named ‘cv2‘
![[leetcode daily question] - 121. The best time to buy and sell stocks](/img/51/ae7c4d903a51d97b70d5e69c6fffaa.png)
[leetcode daily question] - 121. The best time to buy and sell stocks

反射、枚举以及lambda表达式
随机推荐
Interview with data center and Bi business (IV) -- look at the essence of ten questions
USB to serial port parameter configuration function
[five minute paper] reinforcement learning based on parameterized action space
Deep packet inspection using cuckoo filter paper summary
anaconda No module named ‘cv2‘
Sqldeveloper tools quick start
Continuous integration (II) introduction to the basic use of Jenkins
VP视频结构化框架
数据中台、BI业务访谈(四)—— 十个问题看本质
Practical purchasing skills, purchasing methods of five bottleneck materials
【EXPDP导出数据】expdp导出23行记录,且不包含lob字段的表,居然用时48分钟,请大家帮忙看看
C # set different text watermarks for each page of word
什么是传输层协议TCP/UDP???
HTB-Apocalyst
蓝牙BLE4.0-HM-10设备配对指南
[basic] the difference between dynamic link library and static link library
Google tries to introduce password strength indicator for chromeos to improve online security
Chapter 08_ Principles of index creation and design
TI C6000 TMS320C6678 DSP+ Zynq-7045的PS + PL异构多核案例开发手册(3)
About the selection of industrial control gateway IOT serial port to WiFi module and serial port to network port module