Enumeration & annotation & reflection

Share the notes when learning enumeration & annotation & reflection. I hope the big guys can point out the mistakes.


Preface

Learning focus: concepts of enumeration, annotation, and reflection, definition of formats, common methods, and understanding of the methods they use.


One, enumeration

1 Introduction

JDK1.5 introduced a new type-enumeration. Before JDK1.5, we defined constants: public static fianl... It is difficult to manage.
Enumeration, you can group related constants into an enumeration type, and enumeration provides more methods than constants

Used to define a limited number of homogeneous constants, for example:

  • Error level:

      低、中、高
    
  • Four seasons of the year:

      春、夏、秋、冬
    
  • Dry food:

      早饭、午饭、晚饭、夜宵
    
     在枚举类型中定义的常量是该枚举类型的实例。
    

Before JDK1.5

//JDK1.5之前
public class Level {
    
    
    //JDK 1.5之前
    public static final Level LOW = new Level(1);
    public static final Level MEDIUM = new Level(50);
    public static final Level HIGH = new Level(100);

    private int levelValue;

    private Level(int levelValue){
    
    
        this.levelValue = levelValue;
    }

    public int getLevelValue() {
    
    
        return levelValue;
    }

    public void setLevelValue(int levelValue) {
    
    
        this.levelValue = levelValue;
    }
}

public class Demo {
    
    
    public static void main(String[] args) {
    
    
        System.out.println(Level.LOW.getLevelValue());
    }
}

After JDK1.5

public enum Level2 {
    
    
    LOW(30),MEDIUM(15),HIGH(7),URGENT(1);
    private int levalValue;

    private Level2(int levalValue){
    
    
        this.levalValue = levalValue;
    }

    public int getLevalValue() {
    
    
        return levalValue;
    }

    public void setLevalValue(int levalValue) {
    
    
        this.levalValue = levalValue;
    }
}

2. Define the format

权限修饰符 enum 枚举名称 {
    
    
	实例1,实例2,实例3,实例4;
}

public enum Level{
    
    
	LOW(30),MEDIUM(15),HIGH(7),URGENT(1);
	private int levelValue;
	
	private Level(int level Value){
    
    
		this.levelValue=levelValue;
	}
	public intget LevelValue(){
    
    
		returnlevelValue;
	}
}

3. The main method of enumeration

Insert picture description here

4. Enumeration classes that implement interfaces

public enum Level3 implements LShow{
    
    
	LOW(){
    
    
		@Override
		public void show() {
    
    
			System.out.println("低级别");
		}
	},MEDIUM{
    
    
		@Override
		public void show() {
    
    
			System.out.println("中级别");
		}
	},HIGH{
    
    
		@Override
		public void show() {
    
    
			System.out.println("高级别");
		}
	};
}



interface LShow{
    
    
	void show();
}



level3.LOW.show();
level3.HIGH.show();

Precautions:

  1. Once an enumeration is defined, it is best not to try to modify the value inside unless the modification is necessary.
  2. Enumeration class inherits java.lang.Enum class instead of Object class by default
  3. Enumeration classes cannot have subclasses, because their enumeration classes are finalized by default
  4. Only private constructor
  5. When using enumeration in switch, use constant name directly instead of carrying class name
  6. The name attribute cannot be defined because it comes with the name attribute
  7. Do not provide a set method for the attributes in the enumeration class, which does not conform to the original design of the enumeration.

Two, annotation

1 Introduction

Java Annotation, also known as Java annotation, is an annotation mechanism introduced by JDK5.0.

Classes, methods, variables, parameters, and packages in the Java language can all be marked. Unlike annotations, Java annotations can obtain annotation content through reflection. When the compiler generates the class file, the annotations can be embedded in the bytecode. The Java virtual machine can retain the annotation content, and the annotation content can be obtained at runtime. Of course it also supports custom Java annotations.

Mainly used:

  1. Analyze in reflection
  2. Generate help documentation
  3. Tracking code dependency
  4. Compilation format check,
    etc.

2. Learning focus

The key to understanding Annotation is to understand the syntax and usage of Annotation.

Learning steps:

  1. concept
  2. How to use built-in annotations
  3. How to customize annotations
  4. How to get annotation content in reflection

3. Built-in annotations

  • @Override: Override *

      - 定义在java.lang.Override
    
  • @Deprecated: Deprecated *

     - 定义在java.lang.Deprecated
    
  • @SafeVarargs

      - Java 7 开始支持,忽略任何使用参数为泛型变量的方法或构造函数调用产生的警告。
    
  • @FunctionalInterface: functional interface *

      - Java 8 开始支持,标识一个匿名函数或函数式接口。
    
  • @Repeatable: Identifies that an annotation can be used multiple times on the same statement

      - Java 8 开始支持,标识某注解可以在同一个声明上使用多次
    
  • SuppressWarnings: Suppress warning messages during compilation. *

      - 定义在java.lang.SuppressWarnings
    

Three ways to use

1.@SuppressWarnings("unchecked")[^Suppress single-type warnings]
2.@SuppressWarnings("unchecked","rawtypes")[^Suppress multiple types of warnings]
3.@SuppressWarnings("all")[^Suppress All types of warnings]

4. Meta annotation

Introduction: Annotations of other annotations in the scope.

What? ?

@Retention-Identifies how to save this annotation, whether it is only in the code, compiled into the class file, or can be accessed through reflection at runtime.
@Documented-mark whether these annotations are included in the javadoc of the user documentation.
@Target-mark which Java member this annotation should be.
@Inherited-mark this annotation is automatically inherited

  1.子类会继承父类使用的注解中被@Inherited修饰的注解
  2.接口继承关系中,子接口不会继承父接口中的任何注解,不管父接口中使用的注解有没有被@Inherited修饰
  3.类实现接口时不会继承任何接口中定义的注解

5. Custom architecture

Annotation schema
Insert picture description here
definition format

@interface custom annotation name {}

Precautions

  1. The defined annotation automatically inherits the java.lang,annotation.Annotation interface

  2. Each method in the annotation is actually a declared annotation configuration parameter

     方法的名称就是配置参数的名称 			
     	方法的返回值类型,就是配置参数的类型。
     			只能是:基本类型/Class/String/enum
    
  3. The default value of the parameter can be declared by default

  4. If there is only one parameter member, the general parameter name is value

  5. The annotation element must have a value. When we define the annotation element, we often use an empty string and 0 as the default value.

Case

@Documented
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation1{
    
    
	参数类型参数名() default 默认值;
}

Three, reflection

Overview

The JAVA reflection mechanism is to obtain the structure of any class, create an object, obtain methods, execution methods, and attributes in the running state! This function of dynamically obtaining information and dynamically calling object methods in the running state is called the reflection of the Java language mechanism.

Class loader

The Java class loader (JavaClassloader) is a part of the Java runtime environment (JavaRuntimeEnvironment), which 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, AppClassLoader

BootstrapClassLoader (bootstrap class loader):

The loader embedded in the JVM kernel. The loader is written in C++. The main load loads the class library under JAVA_HOME/lib. The boot class loader cannot be used directly by the application.

ExtensionClassLoader (extended class loader):

ExtensionClassLoader is written in JAVA, and its parent class loader is Bootstrap.
It is implemented by sun.misc.Launcher$ExtClassLoader, which mainly loads class libraries in the JAVA_HOME/lib/ext directory.
Its parent loader is BootstrapClassLoader

AppClassLoader (application class loader):

AppClassLoader is an application class loader, responsible for loading all jar and class files in the application classpath directory. Its parent loader is Ext ClassLoader

Insert picture description here
Classes are usually loaded on demand, that is, they are loaded when the class is first used. Thanks to the class loader, the Java runtime system does not need to know files and file systems. When learning class loaders, it is important to master the Java delegation concept.

Parent delegation model: If a class loader receives a class loading request, it will not try to load the class itself, but will forward the request to the parent class loader to complete. This is true for every level of class loader. Therefore, all class loading requests should be passed to the top-level startup class loader, and only when the parent class loader reports that it cannot complete the loading request (the class is not found in its search range), the sub-class loader only Will try to load it myself. The advantage of delegation is to prevent some classes from being loaded repeatedly.

Source code
Insert picture description here
all types of Class objects

To understand a class, you must first obtain the bytecode file object of the class. In Java, after each bytecode file is clamped in memory, there is a corresponding Class type object

Several ways to get Class

1.如果在编写代码时,指导类的名称,且类已经存在,可以通过包名.类名.class得到一个类的类对象

2.如果拥有类的对象,可以通过Class对象.getClass()得到一个类的类对象

3.如果在编写代码时,知道类的名称,可以通过Class.forName(包名+类名):得到一个类的类对象

上述的三种方式,在调用时,如果类在内存中不存在,则会加载到内存!
如果类已经在内存中存在,不会重复加载,而是重复利用!
(一个class文件在内存中不会存在两个类对象)


特殊的类对象

	基本数据类型的类对象:
		基本数据类型.clss
		包装类.type
	基本数据类型包装类对象:
		包装类.class

Get Constructor
Get the construction method of a class through the class object

1.getMethod(StringmethodName,class..clss)
	根据参数列表的类型和方法名,得到一个方法(public修饰的)

2.getMethods();
	得到一个类的所有方法(public修饰的)

3.getDeclaredMethod(StringmethodName,class..clss)
	根据参数列表的类型和方法名,得到一个方法(除继承以外所有的:包含私有,共有,保护,默认)

4.getDeclaredMethods();
	得到一个类的所有方法(除继承以外所有的:包含私有,共有,保护,默认)

Method execution method

invoke(Objecto,Object...para):

	调用方法 ,
		参数1.要调用方法的对象
		参数2.要传递的参数列表

getName()
	获取方法的方法名称

setAccessible(booleanflag)

	如果flag为true则表示忽略访问权限检查!(可以访问任何权限的方法)

Get Field
Get the attributes of a class through the class object

1.getDeclaredField(StringfiledName)
	根据属性的名称,获取一个属性对象(所有属性)
2.getDeclaredFields()
	获取所有属性
3.getField(StringfiledName)
	根据属性的名称,获取一个属性对象(public属性)
4.getFields()
	获取所有属性(public)

Object type of Field property

常用方法:

	1.get(Objecto);
		参数:要获取属性的对象
		获取指定对象的此属性值
	
	2.set(Objecto,Objectvalue);
		参数1.要设置属性值的对象
		参数2.要设置的值
		设置指定对象的属性的值
	
	3.getName()
		获取属性的名称

	4.setAccessible(booleanflag)

		如果flag为true则表示忽略访问权限检查!(可以访问任何权限的属性)

Get annotation information
Get all annotation objects of class/attribute/method

Annotation[] annotations01=Class/Field/Method.getAnnotations();
for(Annotation annotation : annotations01){
    
    
		System.out.println(annotation);
}

Get the annotation object of the class/attribute/method according to the type

注解类型 对象名=(注解类型) c.getAnnotation(注解类型.class);

]

Guess you like

Origin blog.csdn.net/weixin_43515837/article/details/111313022