Hello, today I’m going to share Java annotations and reflections with you. Take out your little book and write them down!

What are annotations

Java annotations, also known as Java annotations, are an Annotation mechanism introduced in JDK5.0.

Classes, methods, variables, parameters, packages, and so on in the Java language can be annotated. Unlike annotations, Java annotations can be retrieved by reflection. Annotations can be embedded into the bytecode when the compiler generates the class file. The Java VIRTUAL machine can retain annotation content and obtain annotation content at runtime. It also supports custom Java annotations.

The difference between annotations and annotations:

Annotations are comments for the machine, and comments are hints for the programmer, which are ignored automatically at compile time.

Usage scenarios for annotations

Compile format check

Reflection resolution

Generate help documents

Trace code dependencies

The role of annotations

As a specific tag, it tells the compiler something. For example, the @override annotation for a method is used by the compiler to verify that the method overrides conform to the specification.

Compile-time dynamic processing, such as dynamically generated code, such as the @data annotations provided by Lombok to dynamically generate getters, setters, toStrings, etc

Runtime dynamic processing, as a carrier of additional information, such as the @Controller layer request mapping path

The most important thing about an annotation is the code that parses it, otherwise the annotation is nothing more than a comment.

Classification of annotations

  • Standard note: Override Deprecated SuppressWarings(ignoring some warnings)

  • Meta-annotations: @target @Retention @Inherited @Documented The purpose of these annotations is to define annotations

  • Custom annotations

Standard annotations

Yuan notes

Definition: a comment that applies to another comment

Target added:

Purpose: To describe the scope of use of the annotation (i.e. where the described annotation can be used)

The values (ElementType) are:

CONSTRUCTOR: Used to describe the CONSTRUCTOR

2.FIELD: Describes the domain

3.LOCAL_VARIABLE: Used to describe local variables

4.METHOD: Used to describe methods

5.PACKAGE: Used to describe packages

6.PARAMETER: Describes parameters

7.TYPE: Used to describe classes, interfaces (including annotation types), or enum declarations

A child class inherits @Inherited annotations from the annotations used by the parent class

In the 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 implements an interface without inheriting any annotations defined in the interface

Custom annotations

When using the @ interface custom annotations, automatic inherited Java. Lang. The annotation. The annotation interface

Analysis:

@interface is used to declare an annotation in the format: public @interface annotation name {define content}

Each of these methods actually declares a configuration parameter whose name is the name of the parameter

The return value type is the type of the parameter (the return value can only be the basic type, Class, String, enum). You can use default to declare the default value of the parameter

If there is only one parameter member, usually the parameter name is value the annotation element must have a value, and when we define the annotation element, we often use an empty string, 0 as the default value

@Target(ElementType.FIELD)

@Retention(RetentionPolicy.RUNTIME)

public @interface AutoWired {

}

reflection

Static language VS dynamic language

Dynamic languages

A dynamic language is a language whose structure can be changed at run time: for example, new functions, objects, and even code can be introduced, existing functions can be deleted, or other structural changes can be made. In layman’s terms, code can change its structure at run time depending on certain conditions

Static language

In contrast to dynamic languages, languages with immutable run-time structures are static languages such as Java, C, and C++

Java is not a static language, but Java can be called a “quasi-dynamic language.” That is, Java is dynamic, and we can use reflection to get features like dynamic languages. The dynamic nature of Java makes programming more flexible

Overview of Java reflection mechanism

Reflection contains the word “negative”, so to explain reflection one must begin with “positive”.

In general, when we use a class, we must know what it is and what it does. We instantiate the class directly, and then operate with the class object (see below)

Student student= new Student (); // Direct initialization, “ortho”

student.setAge(14);

The above initialization of the class object can be understood as “positive”.

Reflection, on the other hand, doesn’t know what class object I’m initializing, so I can’t use the new keyword to create the object.

In this case, we use the reflection API provided by the JDK to make reflection calls:

Results:

The result of executing the above two pieces of code is exactly the same. But the idea completely different, when the first piece of code is not running, you’ve already determined to run the class (Apple), and the second piece of code is learned through the string values at run time to run the class (com) chenshuyi. Reflect. Apple).

As you can see from this simple example, in general we use reflection to get an object:

1. Obtain the Class object instance of the Class

Class CLZ = Class. Class.forname (” com. ZNB. Entity. The User “);

2. Get the Constructor object from the Class object instance

Constructor constructor = clz.getConstructor();

3. Get the reflection class object using the newInstance method of the Constructor object

Object object = constructor.newInstance();

4. Get the Method object of the Method

Clz.getmethod (” setId “, int. Class);

Clz.getmethod (” setPassword “, string.class);

Clz.getmethod (” setUsername “, string.class);

5. Use the Invoke method to call a method

method1.invoke(object, 40);

An invoke (object, “777444”);

Method3. Invoke (object, “555666”);

At this point, we have been able to grasp the basic use of reflection. But to get a better grasp of reflection, you need to have a deeper understanding of the common apis for reflection.

In the JDK, the reflection API can be divided into the following areas: getting reflected Class objects, creating Class objects through reflection, and getting Class property methods and constructors through reflection.

Reflection common API

Gets the Class object in reflection

In reflection, to get a Class or call a method of a Class, we first need to get the Class object of that Class.

In the Java API, there are three ways to get Class objects:

Use the class.forname static method. You can use this method to get Class objects when you know the full pathname of the Class.

Class Uclass1 = Class. Class.forname (” com. ZNB. Entity. The 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 through reflection

There are two main ways to create Class objects through reflection: through the newInstance() method of a Class object and through the newInstance() method of a Constructor object.

Through the Class object’s newInstance() method.

Class uclass= User.class;

User user= (User) uclass.newInstance();

NewInstance () via the Constructor object method

Class uclass= User .class;

Constructor constructor = uclass.getConstructor();

User user= (User )constructor.newInstance();

Class objects created from a Constructor object can select a specific Constructor, whereas only the default no-argument Constructor can be used from a Class object. The following code calls a constructor with arguments 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 attributes, methods, and constructors by reflection

We can get Class attributes through the getFields() method of the Class object, but we can’t get private attributes.

Results:

If you use the getDeclaredFields() method of the Class object, you can get all attributes, including private attributes

Results:

Just like getting a class attribute, if we want to get a private method or constructor, we must use methods with the declared keyword.

Reflection Application Scenario

Java’s reflection mechanism is very useful in building infrastructure, and there is a saying that reflection is the cornerstone of many Java frameworks. And the general application level is rarely used, but this kind of thing, now a lot of open source frameworks have basically given you a good package, their basic need not write. Typically in addition to Hibernate, Spring also uses many reflection mechanisms. The classic is to write the configuration in an XML file or properties, and then parse the XML or Properties in a Java Class to get a string, and then use reflection to get an instance of a Class based on that string, so you can dynamically configure something. Instead of having to go to new or do something else in the code every time, you can change the configuration file in the future, which makes it easier to maintain the code. At the same time, you can also use reflection mechanism to meet some requirements, which may not be able to call another method in the Java class.

In general, there is very little to write, and when to use it depends on the requirements. The reflection mechanism is nothing more than taking the entity object you want from a String and calling it as it was. But if you are writing your own framework, you will use it more often.

How do you instantiate an object when you make software that installs the functionality of a plug-in and you don’t even know the plug-in’s type name? Because the program is plugin-enabled (third-party), it is not known at the time of development. So you can’t get New in your code, but reflection can, by reflection, load the assembly dynamically, and then read the class, check the tag and then instantiate the object, and you get the correct instance of the class.

Without knowing the class name at coding time and reading it from the configuration file at runtime, there is no way to hardcode newClassName() and reflection must be used to create the object. The purpose of reflection is to extend unknown applications. For example, if you write a program that defines some interfaces, any DLL that implements these interfaces can be inserted into the program as a plug-in. So how do you do that? You can do that by reflection. The DLL is loaded into memory, and then through reflection to call the method in the DLL. Many factory patterns use reflection.

Programmers should avoid reflection as much as possible in their business development

Reflection: Reflection naturally has its place in popular libraries such as Spring and Hibernate. But introspecting business code is a bad thing a lot of the time for a number of reasons, and IN general I always advise against reflection.

Performance analysis

Reflection is the ability of a program to analyze itself. Class variables, constructors, methods, and modifiers used to get a class.

Advantages: runtime type determination, dynamic class loading, dynamic proxy using reflection.

Cons: Performance is an issue, reflection is a series of interpreted operations telling the JVM what to do, and performance is much slower than direct Java code.

Well, that’s all for today’s article, hoping to help those of you who are confused in front of the screen