In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly introduces "what is Java annotation and reflection". In daily operation, I believe many people have doubts about what is Java annotation and reflection. The editor consulted all kinds of data and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the questions of "what is Java annotation and reflection"! Next, please follow the editor to study!
What is a comment?
Java annotations (Annotation), also known as Java annotations, is an annotation mechanism introduced by JDK5.0.
Classes, methods, variables, parameters, and packages in the Java language can all be annotated. Unlike annotations, Java dimensions can obtain the content of dimensions through reflection. Annotations can be embedded in bytecode when the compiler generates class files. The Java virtual machine can retain the annotation content, which can be obtained at run time. Of course, it also supports custom Java annotations.
The difference between comments and comments:
Annotations are annotations for the machine, while annotations are hints for programmers, and comments are automatically ignored at compile time.
Usage scenarios of annotations
Compile format check
Analysis in reflection
Generate help documentation
Tracking code dependency
The role of annotations
As a specific tag, inform the compiler of some information. For example, the @ Override annotation of a method is used by the compiler to verify that the rewrite of the method conforms to the specification.
Dynamic processing at compile time, such as dynamically generating code, such as some annotations provided by Lombok @ Data, to dynamically generate getter setter toString, etc.
Run-time dynamic processing, as an additional carrier of information, such as the path to the request mapping of the @ Controller layer
The most important thing for an annotation is to parse the code for the annotation, otherwise the annotation is not as good as the comment.
Classification of annotations
Standard note: Override (method rewriting) Deprecated (obsolete) SuppressWarings (ignore some warnings)
Meta-annotations: @ Target @ Retention @ Inherited @ Documented the purpose of these annotations is to define annotations for annotations
Custom annotation
Standard annotation
Meta annotation
Definition:
Notes acting on other annotations
Target added:
Function: used to describe the scope of use of annotations (that is, where the annotations described can be used)
The values (ElementType) are:
1.CONSTRUCTOR: used to describe constructors
2.FIELD: used to describe the domain
3.LOCAL_VARIABLE: used to describe local variables
4.METHOD: used to describe methods
5.PACKAGE: used to describe packages
6.PARAMETER: used to describe parameters
7.TYPE: used to describe classes, interfaces (including annotation types), or enum declarations
Subclasses inherit annotations modified by @ Inherited in annotations used by the parent class
In an interface inheritance relationship, the child interface does not inherit any annotations in the parent interface, regardless of whether the annotations used in the parent interface are modified by @ Inherited
Class does not inherit annotations defined in any interface when it implements an interface
Custom annotation
When using @ interface custom annotations, the java.lang.annotation.Annotation interface is automatically inherited
Analysis:
@ interface is used to declare an annotation in the format: public @ interface annotation name {definition content}
Each of these methods actually declares a configuration parameter method name that is the parameter name.
The return value type is the type of the parameter (the return value can only be a basic type, Class,String,enum) you can declare the default value of the parameter through default
If there is only one parameter member, the general parameter name is value. The annotation element must have a value. When we define the annotation element, we often use an empty string with 0 as the default.
@ Target (ElementType.FIELD)
@ Retention (RetentionPolicy.RUNTIME)
Public @ interface AutoWired {
}
Reflective static language VS dynamic language
Dynamic language
A dynamic language is a language that can change its structure at run time: for example, new functions, objects, and even code can be introduced, existing functions can be deleted, or other structural changes. To put it more popularly, code can change its structure according to certain conditions at run time.
Static language
Corresponding to dynamic languages, languages with immutable runtime structures are static languages, such as Java, C, C++.
Java is not a static language, but Java can be called a "quasi-dynamic language". That is to say, Java is dynamic to a certain extent, and we can use the reflection mechanism to obtain characteristics similar to dynamic languages. The dynamic nature of Java makes programming more flexible.
Overview of Java reflection Mechanism
reflection contains the word "negative", so if you want to interpret reflection, you must start with "positive".
In general, when we use a class, we must know what it is and what it is used for. So we instantiate the class directly, and then use the class object (see later) to operate.
Student student= new Student (); / / initialize directly, "orthophoto"
Student.setAge (14)
The initialization of the class object like this can be understood as "positive".
Reflection, on the other hand, does not know what the class object I want to initialize at first, and naturally it is impossible to use the new keyword to create the object.
At this point, we use the reflection API provided by JDK to make the reflection call:
Results:
The execution result of the above two pieces of code is actually exactly the same. But the idea is completely different. The first piece of code already determines the class to run (Apple) before it is run, while the second piece of code knows the class to run (com.chenshuyi.reflect.Apple) only by the string value at run time.
As you can see from this simple example, in general we use reflection to get an object:
1. Get the Class object instance of the class
Class clz = Class.forName ("com.znb.entity.User")
two。 Get Class object based on Constructor object instance
Constructor constructor = clz.getConstructor ()
3. Use the newInstance method of the Constructor object to get the reflection class object
Object object = constructor.newInstance ()
4. Get the Method object of the method
Method method1 = clz.getMethod ("setId", int.class)
Method method2 = clz.getMethod ("setPassword", String.class)
Method method3 = clz.getMethod ("setUsername", String.class)
5. Using invoke method to call method
Method1.invoke (object, 40)
Method2.invoke (object, "777444")
Method3.invoke (object, "555666")
At this point, we have been able to master the basic use of reflection. However, if you want to further master reflection, you also need to have a deeper understanding of the common API of reflection.
In JDK, reflection-related API can be divided into the following aspects: obtaining reflected Class objects, creating class objects through reflection, obtaining class attribute methods and constructors through reflection.
Reflection commonly used API to get Class objects in reflection
In reflection, to get a class or call a class's method, we first need to get the Class object of that class.
In Java API, there are three ways to get a Class class object:
Use the Class.forName static method. When you know the full path name of the class, you can use this method to get the Class class object.
Class Uclass1=Class.forName ("com.znb.entity.User")
Use the .class method.
Class Uclass2= User.class
Use the getClass () method of the class object.
User user=new User ()
Class Uclass3=user.getClass ()
Results:
Create class objects by reflection
There are two main ways to create a class object through reflection: through the newInstance () method of the Class object and through the newInstance () method of the Constructor object.
Through the newInstance () method of the Class object.
Class uclass= User.class
User user= (User) uclass.newInstance ()
Through the newInstance () method of the Constructor object
Class uclass= User .class
Constructor constructor = uclass.getConstructor ()
User user= (User) constructor.newInstance ()
Creating a class object through a Constructor object allows you to choose a specific constructor, while a Class object can only use the default no-parameter constructor. The following code calls a constructor with parameters to initialize the class object.
Class uclass= User .class
Constructor constructor = uclass.getConstructor (
Int.class,String.class,String.class)
User user= (User) constructor.newInstance (1,555, 888)
Get class properties, methods, and constructors through reflection
We can get the properties of the Class class through the getFields () method of the Class object, but not the private properties.
Results:
If you use the getDeclaredFields () method of the Class object, you can get all the properties, including private properties.
Results:
As with getting class attributes, when we go to get class methods, class constructors, if we want to get private methods or private constructors, we must use methods with the declared keyword.
Reflection application scenario
Java's reflection mechanism is very useful when working as a basic framework, as the saying goes: reflection mechanism is the cornerstone of many Java frameworks. It is rarely used at the general application level, but now many open source frameworks have basically been packaged for you, and you basically don't need to write it. In addition to Hibernate, Spring typically uses a lot of reflection mechanisms. The classic thing is to write the configuration in the xml file or properties, and then parse the contents of xml or properties in the Java class to get a string, and then use the reflection mechanism to obtain the Class instance of a class according to this string, so that you can dynamically configure something without having to new or do anything else in the code every time. If you want to change it later, you can directly change the configuration file. The code is easy to maintain, and sometimes to meet certain requirements, other methods may not be called directly in the Java class, which can also be achieved through the reflection mechanism.
Generally speaking, I write very little, and when I want to use it depends on the requirements, the reflection mechanism is nothing more than getting the entity object you want according to a String, and then calling its original thing. But if you want to write your own framework, you will use it more often.
When you make a software that can install the plug-in function, you don't even know the type name of the plug-in, how do you instantiate this object? Because the program supports plug-ins (third-party), it is not known at the time of development. So you can't New it in the code, but reflection can, through reflection, dynamically load the assembly, then read out the class, check the tag, and then instantiate the object, and you can get the correct class instance.
If you don't know that class name during the coding phase, if you want to read the class name from the configuration file at run time, there is no way to hard-code newClassName (). Instead, reflection must be used to create the object. The purpose of reflection is to expand unknown applications. For example, if you write a program that defines some interfaces, as long as the dll that implements these interfaces can be inserted into the program as a plug-in. So how to achieve it? It can be done through reflection. Is to load the dll into memory and then call the methods in the dll by reflection. Many factory models use reflection.
Programmers should try to stay away from reflection in their business development.
Reflection: in popular libraries such as Spring and Hibernate, reflection naturally has opportunities to use its talents. However, introspection of business code is not a good thing in many cases, for many reasons, in general, I always advise you not to use reflection.
Performance analysis.
The reflection mechanism is a kind of self-analysis ability of the program. Used to get class variables, constructors, methods, and modifiers for a class.
Advantages: run-time type judgment, dynamic class loading, dynamic proxy using reflection.
Cons: performance is a problem, and reflection is the equivalent of a series of interpretive operations that tell jvm what to do, and performance is much slower than direct java code.
At this point, the study on "what is Java annotations and reflection" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.