A, annotations,
Annotations to define
Java annotations annotations, also called 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, while annotations are hints for the programmer, and are ignored automatically at compile time.
Usage scenarios
- Compile format check
- Reflection resolution
- Generate help documents
- Trace code dependencies
- , etc.
Built-in annotations
Annotation type | Annotations meaning | added |
---|---|---|
@Override | rewrite | Defined in Java. Lang. Override |
@Deprecated | abandoned | Defined in Java. Lang. Deprecated |
@SafeVarargs | Ignore any warnings generated by method or constructor calls that take arguments as generic variables | Java7 support is available |
@FunctionalInterface | Functional interface | Java8 began to support identifying an anonymous function or functional interface |
@Repeatable | Identifies an annotation that can be used more than once on the same declaration | Java8 support is available |
@SuppressWarnings | Suppress compile-time warning messages | Defined in Java. Lang. SuppressWarnings |
Add: three ways to @SuppressWarnings:
- @ SuppressWarnings (” unchecked “)
Suppress a single type of warning
- @ SuppressWarnings (” unchecked “, “rawtypes”)
Suppress multiple types of warnings
- @ SuppressWarnings (” all “)
Suppress all types of warnings
Yuan notes
Definition: a comment that applies to another comment
Meta annotation type:
Annotation type | Annotations meaning |
---|---|
@Retention | Identify how the annotation is stored. Is it only in code, in a class file, or is it accessible through reflection at run time |
@Documented | Marks whether these annotations are included in the user documentation Javadoc |
@Target | Marks which Java member the annotation should be |
@Inherited | Marks this annotation as automatically inherited |
Inherited added:
- 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
Custom annotation framework:
Annotation
与 RetentionPolicy
与 ElementType
。
Every Annotation object, every Annotation object, has a unique RetentionPolicy property; For ElementType attributes, there are 1 to N.
ElementType(Utility type for annotations)
“Every Annotation” is associated with “1 to N ElementTypes.” When an Annotation is associated with an ElementType, it means that the Annotation has a purpose. For example, if an Annotation object is of type METHOD, that Annotation can only be used to modify methods.
type | The type of the object being used |
---|---|
TYPE | Classes, interfaces, enumerations |
FIELD | Field properties (including enumerated constants) |
METHOD | methods |
PARAMETER | The parameter types |
CONSTRUCTOR | A constructor |
LOCAL_VARIABLE | A local variable |
ANNOTATION_TYPE | annotations |
PACKAGE | package |
TYPE_PARAMETER | After 1.8, generics |
TYPE_USE | After 1.8, any type except PACKAGE |
package java.lang.annotation;
public enum ElementType {
TYPE, /* Class, interface (including annotation types), or enumeration declaration */
FIELD, /* Field declarations (including enumeration constants) */
METHOD, /* Method declaration */
PARAMETER, /* Parameter declaration */
CONSTRUCTOR, /* Constructor declaration */
LOCAL_VARIABLE, /* Local variable declaration */
ANNOTATION_TYPE, /* Comments the type declaration */
PACKAGE /* Package declaration */
}
Copy the code
RetentionPolicy(Annotation scope policy)
“Every Annotation” is associated with “1 RetentionPolicy.”
A) If the type of Annotation is SOURCE, it means that the Annotation only exists during the compiler processing, and after the compiler processing, the Annotation is useless. For example, the “@Override” flag is an Annotation. When it decorates a method, it means that the method overrides the parent method. The syntax is checked during compilation, and the “@override” has no effect after the compiler processes it.
B) If the Annotation type is CLASS, it means that the compiler stores the Annotation in the corresponding.class file of the CLASS, which is the default behavior of the Annotation.
C) If the Annotation type is RUNTIME, it means that the compiler stores the Annotation in a class file that can be read in by the JVM.
type | role |
---|---|
SOURCE | Annotations are retained only at the source stage and are erased when the compiler compiles them. The common @override annotation is one of these annotations |
CLASS | Annotations are retained at compile time, but are discarded when the Java VIRTUAL machine loads class files, which is also the “default” for @Retention. @deprecated and @nonnull are such annotations |
RUNTIME | Annotations are retained at run time and can be retrieved by reflection in the program, such as @Controller, @Service, etc. Common in Spring |
package java.lang.annotation;
public enum RetentionPolicy {
SOURCE, /* The Annotation information exists only for the duration of the compiler's processing; it is no longer available after the compiler's processing
CLASS, /* The compiler stores the annotations in the corresponding.class file of the class. The default behavior */
RUNTIME /* The compiler stores the annotations in a class file that can be read in by the JVM */
}
Copy the code
Define the format
@interfaceCustom annotation name {}Copy the code
Matters needing attention
- Definition of the annotations, automatic inherited Java. Lang, the annotation. The annotation interface
- Each method in an annotation is actually a declared annotation configuration parameter
- The name of the method is the name of the configuration parameter
- The return value type of the method is the type of the configuration parameter. The value can be basic /Class/String/enum
- You can declare default values for parameters with default
- If there is only one parameter member, the general parameter name is value
- An annotation element must have a value, and when we define an annotation element, we often use an empty string, 0, as the default.
Annotations are summarized
Runtime annotations come into play in the following steps:
- The reflection call to the annotation causes the dynamic proxy to create a class that implements the annotation
- The real processing object behind the proxy is
AnnotationInvocationHandler
, this class internally maintains a map with key-value pairs of the form< method name defined in annotation, corresponding property name >
- Any call to the annotation’s custom method (leaving aside the method that the dynamic proxy class inherits from Object) will eventually be actually called
AnnotatiInvocationHandler
Invoke method, and the invoke method’s handling of such a method is simple: get the name of the method passed in and look up the map - In the map
memeberValues
The initialization ofAnnotationParser
The method is initialized before the method is called and cached in the map AnnotationParser
And ultimately throughConstantPool
Object to retrieve the corresponding data from the constant pool, further downConstantPool
Object is not going to go too far
Second, the reflection
JAVA reflection mechanism is in the running state, get the structure of any class, create objects, get methods, execute methods, properties;
This ability to dynamically retrieve information at runtime and invoke object methods is known as the Reflection mechanism of the Java language.
Class loader
The Java Classloader is part of the Java Runtime Environment and is responsible for dynamically loading Java classes into the memory space of the Java virtual machine.
Java has three types of loaders by default: BootstrapClassLoader, ExtensionClassLoader, and App ClassLoader.
1, BootstrapClassLoader(bootloader):
A loader embedded in the JVM kernel, written in C++, that loads libraries in JAVA_HOME/lib. The boot loader cannot be used directly by applications.
2. ExtensionClassLoader
ExtensionClassLoader is written in JAVA and its parent class loader is Bootstrap. Launcher$ExtClassLoader is implemented by sun.misc.Launcher$ExtClassLoader, which loads the class libraries in the JAVA_HOME/lib/ext directory. Its parent loader is BootstrapClassLoader
3, App ClassLoader:
App ClassLoader is the application class loader that loads all jar and class files in the application classpath directory. Its parent loader is Ext ClassLoader
Classes are usually loaded on demand, that is, when they are first used. Thanks to the classloader, the Java runtime system does not need to know about files and file systems. It is important to master Java’s concept of delegation when learning about class loaders.
Parental delegation model:
If a classloader receives a classloading request, it does not attempt to load the class itself, but passes the request on to the parent classloader to complete. This is true at every level of class loaders. Therefore, all class loading requests should be passed to the top level of the bootstrap class loader, and the subclass loader will only attempt to load itself if the parent class loader reports that it cannot complete the load request (it did not find the class in its search scope). The advantage of delegation is that some classes are not reloaded.
Loading a Configuration File
- Add the Resource root directory to the project
- Load the resource file through the class loader
- The default is to load files in the SRC directory, but if the project has a resource root directory, it will load files in the resource root directory instead.
Reflection fetch Class
To learn about a class, you must first get the bytecode file object for that class. In Java, each bytecode file, when clamped into memory, has an object of type Class.
1, get Class
1) If you know the name of the class when you write the code and the class already exists, you can use the package name. Class gets the class object of a class
2) If you have an object of a Class, you can get the object of a Class by using Class object.getClass ()
3) If you know the name of a Class when writing code, you can use class.forname (package name + Class name) to get the Class object of a Class
The above three ways, when called. If the class does not exist in memory, it is loaded into memory. If the class already exists in memory, it is not reloaded, but reused.
2. Special class objects
Class object of base datatype: base datatype.class
A wrapper class type
Basic data types Wrapper class object: wrapper class.class
Reflection get Constructor
Gets the constructor of a class from the class object
GetConstructor (array of class objects of the specified parameter type);
The construction method is as follows:
Person(String name,int age)
Copy the code
The code to get this constructor looks like this:
Constructor c = p.getClass().getConstructor(String.class,int.class);
Copy the code
2. Get the constructor array
getConstructors();
Copy the code
Get a single constructor for all permissions
GetDeclaredConstructor (of the parameter typeclassObject array)Copy the code
Get an array of constructors for all permissions
getDeclaredConstructors();
Copy the code
Constructor creates an object
newInstance(Object... para)
Copy the code
Call this constructor to create the corresponding object. Parameter: is a variable parameter of type Object. The order of the parameters passed must match the order of the formal parameter list in the constructor
setAccessible(boolean flag)
Copy the code
If flag is true, access check is ignored! (Methods that can access any permissions)
Reflection Method
Get a class method from the class object
GetMethod (String methodName, class... clss)
Get a method based on the type and method name of the argument list (public modified)
getMethods()
Get all the methods of a class (public modified)
GetDeclaredMethod (String methodName, class... clss)
Get a method based on the type and method name of the argument list (all except inherited: private, common, protected, default)
getDeclaredMethods()
Get all methods of a class (all except inheritance: private, common, protected, default)
2. Method Execution Method
invoke(Object o,Object... para)
- Call method, argument 1. The object to call the method; Parameter 2. List of parameters to be passed
getName()
- Gets the method name of the method
setAccessible(boolean flag)
- If flag is true, access checking is ignored (methods that can access any permission)
Reflection capture Field
1. Get a class attribute from the class object
getDeclaredField(String filedName)
Gets a property object (all properties) based on the property name
getDeclaredFields()
Get all attributes
getField(String filedName)
Get a property object based on the property name (public property)
getFields()
Get all attributes (public)
2. The object type of the Field property
Common methods:
get(Object o)
Parameter: Gets the value of this property for the specified object
set(Object o , Object value)
Parameter 1. The object for which the property value is to be set; Parameter 2. Value to Set Sets the value of the properties of the specified object
getName()
Gets the name of the property
setAccessible(boolean flag)
If flag is true, access check is ignored! (Properties that can access any permissions)
Get annotation information through reflection
Gets all the annotation objects for the class/property/method
Annotation[] annotations01 = Class/Field/Method.getAnnotations();
for (Annotation annotation : annotations01) {
System.out.println(annotation);
}
Copy the code
Gets the annotation object of the class/property/method by type
Annotation type object name = (annotation type) C.getAnnotation (annotation type.class);Copy the code
Introspection Introspector
Java provides a set of apis applied to Javabeans based on reflection
The Bean class:
- A class defined in a package,
- Has a no-parameter constructor
- All properties are private,
- All properties provide get/set methods
- Serialization interface is implemented
Java provides a java.beans package API that encapsulates reflection operations
1. Get Bean class information
Methods:
BeanInfo getBeanInfo(Class CLS) Gets the wrapped object of the Bean Class from the Class information passed in.
Get the array of get/set methods of the bean class
Common methods:
MethodDescriptor[] getPropertyDescriptors():
Copy the code
3, MethodDescriptor
Common methods:
Method getReadMethod()
Gets a get method
Method getWriteMethod();
Gets a set method.
It is possible to return null.