当前位置:网站首页>Explanation and application of annotation and reflection
Explanation and application of annotation and reflection
2022-07-02 06:48:00 【I think starfish_ ninety-eight】
List of articles
annotation
Overview and understanding
The development of annotations has been the trend of the times , Future frameworks are based on annotation + Reflection + Design patterns
JDK Meta annotations in
Yuan notes : Explain and limit the existing annotations ( An annotation that modifies an annotation )
JDK5.0 Provides 4 Standard meta annotation types , Namely :
- Retention: Indicate the overall scope of application of the annotation ( The default is CLASS, Use when reflecting RUNTIME)
- Target: Indicate the level that annotations can modify , For example, class 、 Method 、 Constructors ( Indicate the level that annotations can modify , For example, class 、 Method 、 Constructors …)
- Document: Indicate whether the annotation needs to enter after compilation jdk file
- Inherited: Annotations can be inherited
Use
What can annotations do ?
Generate comments related to the document
Format check at compile time
Trace code dependencies , Implement the function of replacing the configuration file
Notes like this , The complexity of the configuration file is omitted
Custom annotation
- use @interface Declaration notes
- Internally defined members , Usually use value Express
- use default Define the default values of members
- If no member is defined , It's a sign
Implementation process :
1、IDEA in , newly build class file
2、 Write code
①、 Don't write value, Similar to rewrite method override
②、 Write value, Add default
3、 Use in other places
Reflection
Overview and understanding
Reflection is equivalent to mirror , See the structure of the class through the mirror , Existing entity objects can be parsed through reflection
The most important use of reflection is to develop a variety of generic frameworks :
A lot of frames ( such as Spring) It's all configured ( such as Spring adopt XML Configuration mode loading Bean), In order to ensure the universality of the framework , They may load different objects or classes according to the configuration file , Call different methods , You have to use reflection at this time —— The runtime dynamically loads the objects that need to be loaded .
Advantages and disadvantages
advantage
Use reflection mechanism , The code can be matched with , It improves the flexibility and expansibility of the program , Reduce coupling , Improve self adaptability . It allows programs to create and control objects of any class , No hard coding of the target class is required
shortcoming
Performance issues : Using reflection is basically an interpretation operation ,JVM This code cannot be optimized , therefore , Reflection operations are much less efficient than those that are not . Reflection mechanism is mainly used in the system framework that requires high flexibility and scalability , It is not recommended to use in programs with high performance requirements
Security restrictions : Using reflection technology requires the program to run in an environment with no security constraints
Internal exposure : Reflection allows code to perform operations that would not normally be allowed ( Such as accessing private properties and methods ), So using reflection can cause unexpected side effects —— The code has functional errors , Reduce portability . Reflection code breaks abstraction , So when the platform changes , The behavior of the code is likely to change as well
Questions
There are both reflections and new The way to build objects , Which one to use ?
Usually use new, If it is dynamic, use reflection ( For example, the interaction between front and background , You are not sure which method to call , At this time, you can use reflection to dynamically delegate )
Reflection can call private , Encapsulation hides private , Whether the two contradict ?
No contradiction , because Encapsulation is recommended , Reflection depends on where it is used . Neither prohibits private use
Which structures have reflections
Reflection and dynamic proxy
obtain class Examples of several ways
/** * obtain class Examples of several ways */
public static void test3() throws Exception {
//1、 Call the properties of the runtime class
Class clazz1 = Person.class;
System.out.println(clazz1);
//2、 Call through a known object getClass()
Person p1 = new Person();
Class clazz2 = p1.getClass();
System.out.println(clazz2);
//3、class Static methods :forName(String classPath)
Class clazz3 = Class.forName("com.company.Person");
System.out.println(clazz3);
//4、 Using loaders for classes :ClassLoader( Not commonly used )
ClassLoader classLoader = Main.class.getClassLoader();
Class clazz4 = classLoader.loadClass("com.company.Person");
System.out.println(clazz4);
}
/** * expand : Use classLoader Load profile */
public static void test4() throws Exception {
Properties pros = new Properties();
// Mode one : The old way ( Under the default project directory )
FileInputStream fis = new FileInputStream("src\\jdbc.properties");
pros.load(fis);
// Mode two : The way of class loader ( Default src Under the table of contents )
ClassLoader classLoader = Main.class.getClassLoader();
InputStream is = classLoader.getResourceAsStream("jdbc.properties");
pros.load(is);
String username = pros.getProperty("username");
String password = pros.getProperty("password");
System.out.println(" full name :"+username+", password :"+password);
}
Call the specified property 、 Method
/** * call person Specified properties */
public static void testShuxing() throws Exception {
Class<Person> personClass = Person.class;
Person p = personClass.newInstance();
//getDeclaredField: Get the property specified in the runtime class
Field name = personClass.getDeclaredField("name");
// Ensure that the attribute can be operated ( private 、 Public and other permissions can operate )
name.setAccessible(true);
//name.set(null,"TOM");
name.set(p,"TOM");
System.out.println(name.get(p));
}
/** * call person The designated method */
public static void testMethod() throws Exception {
Class<Person> personClass = Person.class;
Person p = personClass.newInstance();
// static state , The normal method is the same
//getDeclaredMethod: Get the method specified in the runtime class
Method showNation = personClass.getDeclaredMethod("showNation", String.class);
// Ensure that the attribute can be operated ( private 、 Public and other permissions can operate )
showNation.setAccessible(true);
//showNation.invoke(p, "CHINA"); Is to call this method directly
// If you take something to receive , Then you receive the return value of this method
//showNation.invoke(null,"CHINA");
Object china = showNation.invoke(p, "CHINA");
System.out.println(china);
}
边栏推荐
- ctf三计
- Improve user experience defensive programming
- js中map和forEach的用法
- CUDA and Direct3D consistency
- Record RDS troubleshooting once -- RDS capacity increases dramatically
- Idea announced a new default UI, which is too refreshing (including the application link)
- 如何调试微信内置浏览器应用(企业号、公众号、订阅号)
- Latex在VSCODE中编译中文,使用中文路径问题解决
- sqli-labs通关汇总-page3
- js把一个数组分割成每三个一组
猜你喜欢
pytest(1) 用例收集规则
The intern left a big hole when he ran away and made two online problems, which made me miserable
Latex在VSCODE中编译中文,使用中文路径问题解决
蚂蚁集团g6初探
CVE-2015-1635(MS15-034 )远程代码执行漏洞复现
Apt command reports certificate error certificate verification failed: the certificate is not trusted
Sentinel rules persist to Nacos
FE - 微信小程序 - 蓝牙 BLE 开发调研与使用
The win10 network icon disappears, and the network icon turns gray. Open the network and set the flash back to solve the problem
Usage of map and foreach in JS
随机推荐
Uploading attachments using Win32 in Web Automation
The use of regular expressions in JS
ZZQ的博客目录--更新于20210601
Pytest (3) parameterize
Tensorrt command line program
2020-9-23 use of QT timer qtimer class.
Latex compilation error I found no \bibstyle &\bibdata &\citation command
Sentry搭建和使用
sprintf_s的使用方法
selenium备忘录:selenium\webdriver\remote\remote_connection.py:374: ResourceWarning: unclosed<xxxx>解决办法
20201002 vs 2019 qt5.14 developed program packaging
蚂蚁集团g6初探
apt命令报证书错误 Certificate verification failed: The certificate is NOT trusted
(第一百篇BLOG)写于博士二年级结束-20200818
Fe - weex uses a simple encapsulated data loading plug-in as the global loading method
Sentry construction and use
Android - Kotlin 下使用 Room 遇到 There are multiple good constructors and Room will ... 问题
Automation - when Jenkins pipline executes the nodejs command, it prompts node: command not found
Alibaba cloud MFA binding Chrome browser
ctf-web之练习赛