当前位置:网站首页>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);
}
边栏推荐
- Detailed definition of tensorrt data format
- sprintf_s的使用方法
- Sublime Text 配置php编译环境
- Flask migrate cannot detect db String() equal length change
- Selenium memo: selenium\webdriver\remote\remote_ connection. Py:374: resourcewarning: unclosed < XXXX > solution
- Win10:添加或者删除开机启动项,在开机启动项中添加在用户自定义的启动文件
- Apt command reports certificate error certificate verification failed: the certificate is not trusted
- A preliminary study on ant group G6
- Win电脑截图黑屏解决办法
- Loops in tensorrt
猜你喜欢

Sentinel Alibaba open source traffic protection component

Latest CUDA environment configuration (win10 + CUDA 11.6 + vs2019)

pytest(1) 用例收集规则

Blog directory of zzq -- updated on 20210601

Fe - wechat applet - Bluetooth ble development research and use

Warp shuffle in CUDA

Sentry搭建和使用

The default Google browser cannot open the link (clicking the hyperlink does not respond)

No process runs when querying GPU, but the video memory is occupied

【文献阅读与想法笔记13】 Unprocessing Images for Learned Raw Denoising
随机推荐
PIP install
解决微信小程序swiper组件bindchange事件抖动问题
Promise中有resolve和无resolve的代码执行顺序
Huawei mindspire open source internship machine test questions
查询GPU时无进程运行,但是显存却被占用了
Fe - wechat applet - Bluetooth ble development research and use
JS modification element attribute flipping commonly used in selenium's Web Automation
How to try catch statements that return promise objects in JS
FE - weex 开发 之 使用 weex-ui 组件与配置使用
ModuleNotFoundError: No module named ‘jieba. analyse‘; ‘ jieba‘ is not a package
Name six schemes to realize delayed messages at one go
20201002 vs 2019 qt5.14 developed program packaging
[daily question 1] write a function to judge whether a string is the string after the rotation of another string.
20201025 Visual Studio2019 QT5.14 信号和槽功能的使用
unittest.TextTestRunner不生成txt测试报告
Sentinel Alibaba open source traffic protection component
2020-9-23 QT的定时器Qtimer类的使用。
Tensorrt command line program
ModuleNotFoundError: No module named ‘jieba.analyse‘; ‘jieba‘ is not a package
VSCODE 安装LATEX环境,参数配置,常见问题解决