Java - annotations and reflection (summary)

Java - annotations and reflection (study notes)

annotation


Java built-in annotations

  • Java defines a set of annotations, a total of 7, 3 in java.lang, and the remaining 4 in java.lang.annotation.

The annotations acting on the code are

  • @Override - Checks if the method is an overriding method. If it is found that the parent class or the referenced interface does not have this method, a compilation error will be reported.

  • @Deprecated - Marks a method as deprecated. If this method is used, a compilation warning will be reported.

  • @SuppressWarnings - instructs the compiler to ignore warnings declared in the annotation.

Annotations (or meta-annotations) that act on other annotations are:

  • @Retention - Identifies how this annotation is saved, whether it is only in the code, or compiled into the class file, or can be accessed through reflection at runtime.

  • @Documented - Marks whether these annotations are included in user documentation.

  • @Target - Marks which Java member this annotation should be.

  • @Inherited - marks which annotation class this annotation is inherited from (the default annotation is not inherited from any subclass)

Starting with Java 7, 3 additional annotations have been added:

  • @SafeVarargs - Supported since Java 7, ignores warnings from any method or constructor invocation that uses a generic variable as an argument.

  • @FunctionalInterface - Supported in Java 8, identifies an anonymous function or functional interface.

  • @Repeatable - Supported by Java 8, it indicates that an annotation can be used multiple times on the same declaration.


How to customize annotations

  • When using @interface custom annotation, it automatically inherits the java.lang.annotation.Annotation interface

  • analyze :

  • @ interface is used to declare an annotation, format: public @ interface annotation name { definition content }

  • Each of these methods actually declares a configuration parameter.

  • The name of the method 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).

  • The default value of the parameter can be declared by default If there is only one parameter member,

  • The general parameter name is value. (If the value has only one value, the value can also be removed)

  • Annotation elements must have values. When we define annotation elements, we often use empty strings and 0 as the default value.


reflection


what is reflection

  Topic introduction: When a java class is compiled and executed (in memory), a corresponding .Class file (that is, a Class object) will be automatically generated, and a class has only one corresponding Class object in memory. We cannot manually create this Class object, and it contains the entire structural information of the corresponding class, just like a mirror, displaying the class information on the mirror. We can only use the method of this Class to obtain all the information methods or operations of the corresponding class, instead of calling its method directly through the object of the new class.

  The process of obtaining the information corresponding to the class through the Class is like operating in front of a mirror, and operating the class through the information mapped from the class to the Class object. This process of operating the ontology by mapping information is reflection.

      If you compare a class to a person, Class is a mirror, and compilation and execution is compared to going out, then you will look in the mirror every time you go out, and your image will be reflected on the mirror, and you can get information about you through the mirror: such as what you are wearing Clothes, names on name tags, etc. This process of obtaining information through the mirror is called reflection. Or when you blow your hair in the mirror, you look at the hair blowing through the information reflected in the mirror, instead of directly looking at the hair blowing.

The types that will automatically generate Class objects are

  • Class, interface, [], [] [], enumeration, annotation, primitive type, void and other data types will automatically generate a corresponding Class object when loading

  • A data type has only one Class object, and it is automatically created when loading. We can only get the method of getting a Class instance that cannot be created manually: Get an instance of the Class class .


use of reflection

Introducing the concept: the dynamism of java

Introduce the concept:
dynamic language: it means that the code can change its own structure according to certain conditions at runtime. Such as: Object-C, C#, JavaScript, PHP, Python, etc.
Static language: Corresponding to dynamic language, a language whose runtime structure is immutable is a static language. Such as Java, C, C++.

Java is not a dynamic language, but Java can be called a "quasi-dynamic language". We can use java's reflection mechanism to obtain features similar to dynamic languages. Reflexion (reflection) is the key to Java being regarded as a dynamic language. The reflection mechanism allows the program to obtain the internal information of any class by means of the Reflexion API during execution, and can directly manipulate the internal properties and methods of any object.

  • Reflection-related main API > implement reflection through the methods inside these classes (emphasis is on Class)

  • java.lang.Class : represents a class

  • java.lang.reflect.Method : Represents a method of a class

  • java.lang.reflect.Field : represents a member variable of a class

  • java.lang.refiect.Constructor : represents the constructor of the class

  • .......

The main idea of ​​using reflection:

  • We can obtain all the information of the corresponding class through reflection, that is, the Class object, and operate through the obtained information.

  • Acquisition method: Obtain, call or operate the information, attributes or methods of the corresponding class through the Method, Filed, and Constructior objects returned by the methods of the Class class object (you can check the documentation). Furthermore, annotation information of classes, fields, etc. can also be obtained.

Through reflection (that is, with the Class object), what can be done?

Taking the User class as an example,
the main premise: there must be a Class object of the User class. Such as:
//Get a Class object
//Get the Class object of the User class through the Class class
Classc1=Class.forName("test04_reflection.User");//"The package path of the User class"
  • Create an object of the User class through the Class object (two ways):

  • The first is a no-argument structure.

Construct a User object user through the newInstance() method of the User's Class object (c1_User).
⚠️ Note: 1. The class must have a parameterless constructor. 2. The access rights of the constructor of the class should be sufficient.
  • The second type has a parameter structure.

Obtain the parameterized constructor of User's declaration through Class, and construct a new user through this constructor
  • Obtain the method through the Class object, and operate the method object on the User class object in reverse.

  • Obtain attributes through the Class object, and reversely operate on the User class object through the attribute object.

⚠️Supplement: setAccessible()

  • Method, Field, and Constructor objects all have setAccessible() methods.

  • The function of setAccessible is to enable and disable the switch of access security check.

  • A parameter value of true indicates that the reflected object should cancel the Java language access check when it is used.

  • Improve the efficiency of reflection. If reflection must be used in the code, and the code needs to be called frequently, please set it to true.

  • Makes private members that are otherwise inaccessible accessible

  • A parameter value of false indicates that the reflected object should implement Java language access checks

Suggestion: Get familiar with the jdk1.8 document about the methods encapsulated in the Class class, Method class, and Field class

Advantages and disadvantages of reflection

  • Advantages: Dynamic object creation and compilation can be realized, showing great flexibility!

  • Disadvantages: Through performance analysis , it can be concluded that reflection has an impact on performance. Using reflection is basically an interpreted operation, we can tell the JVM, what we want to do and it does what we want. Such operations are always slower than performing the same operations directly.

Guess you like

Origin blog.csdn.net/weixin_41606115/article/details/129030915