java Quick Start

Keywords: Java Eclipse

1. Comments

The importance of annotations goes without saying that no matter what code annotations we write, how do java's annotations and annotation templates work?Let's take a look.

package frist;
/*
 * @Description HelloWorld class
 * @Author Wang Yan-collar
 **/
class HelloWorld {
    /*
    This is the main entry point for our Java programs.
    main Method is also the main thread of the program.
    */
    public static void main(String[] arg)
    {
        //output
       System.out.println("wyl");
    }
}

1.1 Comments

As you can see above, there are three main types of comments for java
Single line comment: can only comment on the current line, starting with //until the end of the line

 //output

Multiline comment: Comment on a piece of text, starting with /*, */ending!

 /*
    This is the main entry point for our Java programs.
    main Method is also the main thread of the program.
 */

Document Note: Used to produce API documents, in conjunction with JavaDoc.

/*
 * @Description HelloWorld class
 * @Author Wang Yan-collar
 **/

1.2 idea Annotation Template Configuration

1.2.1 Defines comments for java file headers

File => setting => editor => File and Code Templates-class -Includes

/**
  * @Creator Wang Yanju
  *@Creation Time ${DATE}
  *Describe Todo
**/

That's what happens when you create a class

1.2.2 Comment on Methods in java classes

Step 1 Check Enable Live Templates
First check Enable Live Templates in the previous step

Step 2 Create a new Group
Next, open LiveTemplates and create a new Group
Figure:

Enter the group name you want in the pop-up window, wyl

Where: Abbreviation is the shortcut key, the corresponding method comment template is prompted when you type w, and j is the class's comment template

Templete Text
Comment content, $$for dynamic template parameter click Edit Vaariables to select the corresponding dynamic value.

/*
 * @Description: TODO
 * @Author Wang Yanju
 * @Time 2021/7/12
 * @Version 1.0
 */
public class wyl {
    /**
     *@describe
     *@Parameter [str]
     *@Return value [java.lang.String]
     *@Creator Wang Yanju
     *@Creation time 2021/7/12
     *@Modify people and other information
     */
    public String CommentTemplate(String str)
    {
        return str;
    }
}

2. Keyword

KeywordExplain
privateAn access control method: Private mode
protectedAn access control method: Protected Mode
publicOne way to access control: shared mode
abstractIndicates that a class or member method has abstract properties
classclass
extendsIndicates that one type is a subtype of another type, where common types are classes and interfaces
finalUsed to describe the final property, indicating that a class cannot derive subclasses, that member methods cannot be overridden, or that the values of member fields cannot be changed
implementsIndicates that a class implements a given interface
interfaceInterface
nativeThe method used to declare a method is implemented by a computer-related language such as C/C++/FORTRAN
newUsed to create a new instance object
staticIndicates static property
strictfpUsed to declare FP_strict (single or double precision floating point) expressions follow the IEEE 754 Arithmetic Specification
synchronizedIndicates that a piece of code needs to be executed synchronously
transientDeclare member fields that are not serialized
volatileIndicates that two or more variables must change synchronously
breakJump out of a block ahead of time
continueBack to the beginning of a block
returnReturn data from member methods
doUsed in do-while loop structure
whileUsed in loop structure
ifIntroduction to conditional statements
elseUsed in conditional statements to indicate a branch when a condition is not established
forA Leader Word of Circular Structure
instanceofUsed to test whether an object is an instance object of a specified type
switchLeader words for branch statement structure
caseUsed in a switch statement to represent one of its branches
defaultDefault, for example, used in a switch statement to indicate a default branch
tryTry a block that might throw an exception
catchUsed in exception handling to catch exceptions
throwThrow an exception
throwsDeclare all exceptions that need to be thrown in the currently defined member method
importIndicates that the specified class or package is to be accessed
packagepackage
booleanOne of the basic data types, Boolean type
byteOne of the basic data types, byte type
charOne of the basic data types, character type
doubleOne of the basic data types, double-precision floating-point type
floatOne of the basic data types, single-precision floating-point type
intOne of the basic data types, integer type
longOne of the basic data types, long integer type
shortOne of the basic data types, short integer type
superIndicates a reference to the parent type of the current object or a construction method for the parent type
thisReference to the current instance object
voidDeclare that the current member method does not return a value
gotoKeep keywords, no specific meaning
constKeep keywords, no specific meaning

3. Data type

3.1. Data type conversion

3.1.1 Automatic Type Conversion

Automatic type conversion: Small data types can be automatically converted to large data types.

Note: If the lower type is char, the conversion to the higher type (integer) will be converted to the corresponding ASCII code value

3.1.2 Cast

Forced type conversion, also known as styling, is used to explicitly convert a numeric type.
(type)var, the type in the operator'()'indicates the target data type to which the value VaR is to be converted.The condition is that the converted data type must be compatible.

double x = 3.14;
int nx = (int)x; //Value 3
char c = 'a';
int d = c+1;
System.out.println(d); //98
System.out.println((char)d); //b

3.1.3. Packaging Class Transition Type Conversion

eg1:int i=Integer.parseInt("123")
Note: This method can only be used to convert strings to integer variables
eg2: float f=Float.valueOf("123").floatValue()
Description: The example above converts a string into a Float object and then calls the floatValue() method of the object to return its corresponding float value.
eg3: boolean b=Boolean.valueOf("123").booleanValue()
Description: The example above converts a string into a Boolean object and then calls the booleanValue() method of the object to return its corresponding Boolean value.
eg4:double d=Double.valueOf("123").doublue()
Description: The example above converts a string into a Double object and then calls the object's doublue() method to return its corresponding double value.
eg5: long l=Long.valueOf("123").longValue()
Description: The example above converts a string into a Long object and then calls the longValue() method of the object to return its corresponding long value.
eg6: char=Character.valueOf("123").charValue()
Description: The example above converts a string into a Character object

4. Constants, Variables, Operators

constant

What is a variable: is the amount that can be changed!
We manipulate data in a storage space through variables, which refer to that storage space!The spatial location is determined, but placed inside
What value is uncertain!Java is a strongly typed language, and each variable must declare its type.

//Data type variable name = value;You can declare multiple variables of the same type separated by commas.

Matters needing attention:
Each variable has a type, which can be either a basic type or a reference type.
The variable name must be a valid identifier.
Variable declarations are a complete statement, so each declaration must end with a semicolon
Variable Scope
Class variable (static variable): A variable independent of the method, modified with static.
Instance variable (member variable): A variable independent of the method, but without a static modifier.
Local variable: A variable in a class's method.

variable

Constant: The value cannot be changed after initialize!Value that will not change.

final Constant name=value;
final double PI=3.14;

Naming Specification

  1. All variables, methods, class names: see name
  2. Class member variables: lowercase first letter and hump principle: monthSalary
  3. Local variables: lowercase first letter and hump principle
  4. Constants: uppercase letters and underscores: MAX_VALUE
  5. Class name: capitalization and hump principle: Man, GoodMan
  6. Method Name: First letter lowercase and hump principle: run(), runRun()

operator

The Java language supports the following operators:
Arithmetic operators: +, -, /,%, ++, -
Assignment Operator=
Relational operator: >, <, >=, <=, ==,!=instanceof
Logical Operator: &amp,|,!
Bit operators: &, |, ^, ~, >, <, >> (Learn!!!)
Conditional operator?:
Extended assignment operator: +=, -=, =, /=

5.java flow control

if...else, while, do...while, for, switch...case is not covered here.
Jump:
return
return returns from a method and gives control to the order in which it was called;Or end the current program directly;
break
break statements are often used to force the exit of the current loop in for, while, do /. while loop statements.
continue
The continue statement is used to skip this loop and execute the next one;

6. Methods

So what is the method?
Java methods are a collection of statements that together perform a function.
Method is an ordered combination of steps to solve a class of problems
Method contained in class or object
Methods are created in programs and referenced elsewhere
Principle of design method: The intent of method is function block, which is a set of statement blocks that implement a function.When we design our methods, the most important thing is
To keep the atomicity of a method, one method only performs one function, which is beneficial to our later expansion.
Advantages of the method
Make the program shorter and clearer.
Favors program maintenance.
It can improve the efficiency of program development.
Improved code reuse.

Definition

Modifier Return Value Type Method Name(Parameter Type Parameter Name){
...
Method Body
...
return Return value;
}

**Modifier: **Modifier, which is optional, tells the compiler how to call this method.The access type of this method is defined.
**Return value type: **Method may return a value.The returnValueType is the data type of the method return value.Some methods are required for execution
The operation did not return a value.In this case, returnValueType is the keyword void.
**Method name: ** is the actual name of the method.The method name and the parameter table together make up the method signature.
** Parameter type: ** The parameter looks like a placeholder.When a method is called, a value is passed to the parameter.This value is called an argument or variable.ginseng
A list of numbers refers to the type, order, and number of parameters of a method.Parameters are optional and the method may not contain any parameters.
Formal parameter: Data used to receive external input when a method is called.
Argument: The data actually passed to the method when the method is called.
** Method body: ** Method body contains specific statements that define the function of the method.

overload

That is, two methods of a class have the same name but different parameter lists.

Variable parameters

In the method declaration, add an ellipsis (...) after specifying the parameter type.
Only one variable parameter can be specified in a method, it must be the last parameter of the method.Any normal parameter must sound before it
Ming.

typeName... parameterName

recursion

Call yourself

7. Arrays

Definition of the array:

An array is an ordered collection of data of the same type.
Arrays describe several data of the same type, arranged and combined in a certain order.
Each data is called an array element, and each array element can be accessed through a subscript.

Four basic characteristics of arrays:

  1. Its length is determined.Once an array is created, its size cannot be changed.
  2. Its elements must be of the same type, and mixed types are not allowed.
  3. Elements in an array can be of any data type, including basic and reference types.
  4. Array variables are of reference type, and arrays can also be viewed as objects, where each element in the array corresponds to a member variable of the object

Array declaration

dataType[] arrayRefVar; // Preferred method
 or
dataType arrayRefVar[]; // The effect is the same, but not the preferred method

Create Array

arrayRefVar = new dataType[1 arraySize];

The elements of an array are accessed through an index.Array indexes start at 0, so index values range from 0 to arrayRefVar.length-1.

Three Initializations

initiate static
In addition to using the new keyword to produce arrays, you can also allocate space and assign values to array elements directly while defining the arrays.

int[] a = {1,2,3};
Man[] mans = {new Man(1,1),new Man(2,2)};

dynamic initialization
Array definitions, allocation of space to array elements, assignment operations, and separation.

int[] a = new int[2];
a[0]=1;
a[1]=2;

Default initialization of arrays
An array is a reference type whose elements correspond to instance variables of a class, so once space is allocated to the array, each element of the array is also factual
The instance variable is implicitly initialized in the same way.

public static void main(String[] args) {
int[] a=new int[2];
boolean[] b = new boolean[2];
String[] s = new String[2];
System.out.println(a[0]+":"+a[1]); //0,0
System.out.println(b[0]+":"+b[1]); //false,false
System.out.println(s[0]+":"+s[1]); //null, null
}

Array Boundary

Subscript's legal range: [0, length-1], error will be reported if it crosses the boundary;

for and For-Each loops

for(type element: array){
System.out.println(element);
}
for (int i = 1; i < myList.length; i++) {
System.out.println(myList[i]);
}

Multidimensional Array

type[][] typeName = new type[typeLength1][1 typeLength2];

Arrays class

Array's tool class java.util.Arrays
The java.util.Arrays class makes it easy to manipulate arrays. You need a guide before you can use it!
It has the following common functions:
Assign values to arrays: through the fill method.
Sort the arrays in ascending order by the sort method.
Compare arrays: Compare the values of elements in an array by the equals method.
Find array elements: Binary lookup of sorted arrays can be performed by the binarySearch method.
Convert to list: Convert through asList(a)

8. Object Oriented

Everything is an object!!!Objects are concrete instances of abstract concepts.

Organize code as classes, and organize (encapsulate) data as objects is object-oriented

inherit

Inheritance is a cornerstone of java's object-oriented programming technology because it allows you to create hierarchical classes.

class Parent Class {
}
class Subclass extends Parent Class {
}

public interface A {
    public void eat();
    public void sleep();
}
 
public interface B {
    public void show();
}
 
public class C implements A,B {
}

Why inherit because there are duplicates.So inherit, and we know that.The parent is the definition or rule of the public part

Java does not support multiple inheritance (it can inherit only one class), but it does support multiple inheritance.

Characteristic

  • Subclasses have properties, methods that are not private s of the parent class.

  • Subclasses can have their own properties and methods, that is, they can extend the parent class.

  • Subclasses can implement their parent's methods in their own way.

  • Java inheritance is single inheritance, but it can be multiple inheritance. Single inheritance means that a subclass can only inherit one parent class. Multiple inheritance means that class B inherits class A, class C inherits class B, so according to the relationship, class B is the parent class of class C, class A is the parent class of class B, which is a feature of Java inheritance different from C++ inheritance.

  • Enhanced coupling between classes (inheritance disadvantage, high coupling results in tighter code connections and less code independence)

super and this keywords

class Animal {
  void eat() {
    System.out.println("animal : eat");
  }
}
 
class Dog extends Animal {
  void eat() {
    System.out.println("dog : eat");
  }
  void eatTest() {
    this.eat();   // this calls its own method
    super.eat();  // super calls parent method
  }
}
 
public class Test {
  public static void main(String[] args) {
    Animal a = new Animal();
    a.eat();
    Dog d = new Dog();
    d.eatTest();
  }
}
animal : eat
dog : eat
animal : eat

final keyword
The final keyword declares that a class can be defined as an inheritable, final class.

class SuperClass {
  private int n;
  SuperClass(){
    System.out.println("SuperClass()");
  }
  SuperClass(int n) {
    System.out.println("SuperClass(int n)");
    this.n = n;
  }
}
// SubClass Class Inheritance
class SubClass extends SuperClass{
  private int n;
  
  SubClass(){ // Automatically invoke parameterless constructor of parent class
    System.out.println("SubClass");
  }  
  
  public SubClass(int n){ 
    super(300);  // Call the constructor with parameters in the parent class
    System.out.println("SubClass(int n):"+n);
    this.n = n;
  }
}
// SubClass2 Class Inheritance
class SubClass2 extends SuperClass{
  private int n;
  
  SubClass2(){
    super(300);  // Call the constructor with parameters in the parent class
    System.out.println("SubClass2");
  }  
  
  public SubClass2(int n){ // Automatically invoke parameterless constructor of parent class
    System.out.println("SubClass2(int n):"+n);
    this.n = n;
  }
}
public class TestSuperSub{
  public static void main (String args[]){
    System.out.println("------SubClass Class Inheritance------");
    SubClass sc1 = new SubClass();
    SubClass sc2 = new SubClass(100); 
    System.out.println("------SubClass2 Class Inheritance------");
    SubClass2 sc3 = new SubClass2();
    SubClass2 sc4 = new SubClass2(200); 
  }
}
------SubClass Class Inheritance------
SuperClass()
SubClass
SuperClass(int n)
SubClass(int n):100
------SubClass2 Class Inheritance------
SuperClass(int n)
SubClass2
SuperClass()
SubClass2(int n):200

Constructor

A subclass does not inherit its parent's constructor (constructor method or constructor), it is only called (implicit or explicit).If the constructor of the parent class has parameters, the constructor of the parent class must be explicitly invoked through the super keyword in the constructor of the child class with an appropriate list of parameters.

If the parent constructor has no parameters, then there is no need to call the parent constructor using the super keyword in the constructor of the child class, and the parameterless constructor of the parent class is automatically called.

Override and Overload

Override

Rewrite is the process by which a subclass rewrites the implementation of a method that allows access to the parent class, and neither the return value nor the parameter can be changed.That is, the shell is unchanged and the core is rewritten

class Animal{
   public void move(){
      System.out.println("Animals can move");
   }
}
 
class Dog extends Animal{
   public void move(){
      System.out.println("Dogs can run and walk");
   }
}
 
public class TestDog{
   public static void main(String args[]){
      Animal a = new Animal(); // Animal Object
      Animal b = new Dog(); // Dog object
      a.move();// Methods to execute Animal classes
      b.move();//Methods to execute Dog classes
   }
}
Animals can move
 Dogs can run and walk

Override rules for methods

  • The parameter list must be identical to the parameter list of the overridden method.

  • The return type can be different from the return type of the overridden method, but it must be a derived class of the parent's return value (java5 and earlier versions of the return type are the same, java7 and later versions can be different).

  • Access cannot be lower than the method overridden in the parent class.For example, if a method of a parent class is declared public, overriding the method in a subclass cannot be declared protected.

  • A member method of a parent class can only be overridden by its subclasses.

  • Methods declared final cannot be overridden.

  • Methods declared as static cannot be overridden, but can be declared again.

  • If the child and parent are in the same package, then the child can override all methods of the parent except those declared as private and final.

  • If the child and parent are not in the same package, then the child can only override non-final methods declared as public and protected by the parent.

  • The overridden method can throw any non-mandatory exception, regardless of whether the overridden method throws an exception or not.However, overridden methods cannot throw new mandatory exceptions, or broader mandatory exceptions than those declared by overridden methods, or vice versa.

  • The construction method cannot be overridden.

  • If you cannot inherit a class, you cannot override its methods.

Overload

Overloading is within a class with the same method name but different parameters.The return types can be the same or different.

Each overloaded method (or constructor) must have a unique list of parameter types.

The most common is the overloading of the constructor.

public class Overloading {
    public int test(){
        System.out.println("test1");
        return 1;
    }
 
    public void test(int a){
        System.out.println("test2");
    }   
 
    //The following two parameter types are in different order
    public String test(int a,String s){
        System.out.println("test3");
        return "returntest3";
    }   
 
    public String test(String s,int a){
        System.out.println("test4");
        return "returntest4";
    }   
 
    public static void main(String[] args){
        Overloading o = new Overloading();
        System.out.println(o.test());
        o.test(1);
        System.out.println(o.test(1,"test3"));
        System.out.println(o.test("test4",1));
    }
}

Overload rules:

  • The overloaded method must change the parameter list (the number or type of parameters are different);

  • Overloaded methods can change the return type;

  • Overloaded methods can change access modifiers;

  • Overloaded methods can declare new or broader check exceptions;

  • Methods can be overloaded in the same class or in a subclass.

  • The return value type cannot be used as a criterion for distinguishing overloaded functions.

    DifferencesOverloading methodsoverride method
    parameter listMust be modifiedMust not be modified
    Return typeCan be modifiedMust not be modified
    abnormalCan be modifiedCan be reduced or deleted, and must not throw new or wider exceptions
    VisitCan be modifiedMust not make more restrictions (can reduce restrictions)

polymorphic

Polymorphism is the ability of the same behavior to have multiple forms or forms.

Polymorphism is the same interface that uses different instances to perform different operations.

Polymorphism is the manifestation of many forms of objects.

Advantages of polymorphism

  1. Eliminating coupling between types
  2. Replaceability
  3. Scalability
  4. Interface
  5. flexibility
  6. Simplification

Three Necessary Conditions for the Existence of Polymorphisms

inherit
Rewrite
Parent reference points to child class object: Parent p = new Child();

class Shape {
    void draw() {}
}
 
class Circle extends Shape {
    void draw() {
        System.out.println("Circle.draw()");
    }
}
 
class Square extends Shape {
    void draw() {
        System.out.println("Square.draw()");
    }
}
 
class Triangle extends Shape {
    void draw() {
        System.out.println("Triangle.draw()");
    }
}

virtual function

Virtual functions exist for polymorphism.

There is no concept of virtual function in Java. Its normal function is equivalent to C++ virtual function. Dynamic binding is the default behavior of Java.If you don't want a function to have a virtual function feature in Java, you can add the final keyword to make it non-virtual.

Implementation of polymorphism

Mode 1: Rewrite:

Mode 2: Interface

Mode three: abstract classes and methods

abstract class

Classes with abstract methods are abstract classes, which are declared using the abstract keyword.

abstract class A{//Define an abstract class
	public void fun(){//General method
		System.out.println("Method with method body");
	}
	public abstract void print();//Abstract method, no method body, decorated with abstract keyword
	
}

Inherit abstract class

We can inherit the properties of the Employee class in the following ways

Principles for using abstract classes
(1) The abstract method must be public or protected (because if it is private, it cannot be inherited by a subclass, and the subclass cannot implement the method), which defaults to public;
(2) Abstract classes cannot be instantiated directly and need to be handled by subclasses in an upward transition manner;
(3) Abstract classes must have subclasses. With extends inheritance, only one subclass can inherit from an abstract class.
(4) Subclasses (if not abstract classes) must override all abstract methods in the abstract class (if subclasses do not implement abstract methods in the parent class, they must also be defined as abstract classes.)

package com.wz.abstractdemo;

abstract class A{//Define an abstract class
	
	public void fun(){//General method
		System.out.println("Method with method body");
	}
	
	public abstract void print();//Abstract method, no method body, decorated with abstract keyword
	
}
//single inheritance
class B extends A{//Class B is a subclass of abstract class and a common class

	@Override
	public void print() {//Force override
		System.out.println("Hello World !");
	}
	
}
public class TestDemo {

	public static void main(String[] args) {
		A a = new B();//Upward Transition
		
		a.print();//Methods overridden by subclasses
	}
}
Hello World !

encapsulation

Encapsulation is a method of packaging and hiding the implementation details of abstract functional interfaces.

Encapsulation can be thought of as a protective barrier against random access of the class's code and data to code defined by an external class.

Access to code and data for this class must be controlled through a strict interface.

The main function of encapsulation is that we can modify our own implementation code without modifying the program snippets that call our code.

Proper encapsulation makes your code easier to understand and maintain, and also enhances its security.

Advantages of packaging

  1. Good packaging reduces coupling.
  2. The structure inside the class can be modified freely.
  3. You can control member variables more accurately.
  4. Hide information to achieve details.

Interface

In the JAVA programming language, it is an abstract type, a collection of abstract methods, and interfaces are usually declared as interfacets.A class inherits the abstract method of an interface by inheriting it.

Interface and Class Similarity

  1. An interface can have multiple methods.
  2. The interface file is saved in the file at the end of.java with the interface name as the file name.
  3. The byte code file for the interface is saved in the file at the end of the.class.
  4. The byte code file corresponding to the interface must be in the directory structure that matches the package name.

Differences between interfaces and classes

  1. Interfaces cannot be used to instantiate objects.
  2. Interface has no construction method.
  3. All methods in an interface must be abstract, and non-abstract methods in an interface after Java 8 can be modified with the default keyword.
  4. Interfaces cannot contain member variables except static and final variables.
  5. Interfaces are not inherited by classes, but are implemented by classes.
  6. Interfaces support multiple inheritance.

Interface characteristics

  1. Each method in an interface is also implicitly abstract, and the method in the interface is implicitly specified as public abstract (only public abstract, other modifiers will error).
  2. Interfaces can contain variables, but variables in an interface are implicitly specified as public static final variables (and can only be public, and compilation errors are reported with private s).
  3. Methods in an interface cannot be implemented in an interface, only the classes that implement the interface can implement the methods in the interface.

Differences between abstract classes and interfaces

  1. Methods in abstract classes can have body, that is, they can implement specific functions of methods, but methods in interfaces cannot.

  2. Member variables in abstract classes can be of various types, while member variables in interfaces can only be of public static final type.

  3. Interfaces cannot contain static code blocks and static methods (methods decorated with static), while abstract classes can have static code blocks and static methods

  4. A class can inherit only one abstract class, while a class can implement multiple interfaces.

[visibility] interface Interface Name [extends Other interface names] {
        // Declare Variables
        // Abstract method
}
/* Filename: NameOfInterface.java */
import java.lang.*;
//Introducing packages
 
public interface NameOfInterface
{
   //Any type of final, static field
   //Abstract method
}

Interfaces have the following characteristics

  • Interfaces are implicitly abstract, so you do not need to use the abstract keyword when declaring an interface.
  • Each method in an interface is also implicitly abstract, and the abstract keyword is not required when declared.
  • Methods in interfaces are public.

enumeration

Enumerations are special classes that generally represent a set of constants. Each enumeration is implemented internally through a Class, and all enumeration values are public static final.

enum Color
{
    RED, GREEN, BLUE;
}
 
public class Test
{
    // Execute Output Results
    public static void main(String[] args)
    {
        Color c1 = Color.RED;
        System.out.println(c1);
    }
}
RED

values(), ordinal(), and valueOf() methods

enum-defined enumeration classes inherit the java.lang.Enum class by default and implement two interfaces, java.lang.Seriablizable and java.lang.Comparable.

The values(), ordinal(), and valueOf() methods are in the java.lang.Enum class:

  • values() returns all the values in the enumeration class.

  • The ordinal() method finds the index of each enumeration constant, just like an array index.

  • The valueOf() method returns an enumeration constant for the specified string value.

    enum Color
    {
        RED, GREEN, BLUE;
    }
     
    public class Test
    {
        public static void main(String[] args)
        {
            // Call values()
            Color[] arr = Color.values();
            // Iterative Enumeration
            for (Color col : arr)
            {
                // View Index
                System.out.println(col + " at index " + col.ordinal());
            }
            // Use valueOf() to return an enumeration constant, non-existent error IllegalArgumentException
            System.out.println(Color.valueOf("RED"));
            // System.out.println(Color.valueOf("WHITE"));
        }
    }
    
    RED at index 0
    GREEN at index 1
    BLUE at index 2
    RED
    

    enumerator

    Enumerations, like ordinary classes, can use their own variables, methods, and constructors. Constructors can only use private access modifiers, so they cannot be called externally.

    enum Color
    {
        RED, GREEN, BLUE;
     
        // Constructor
        private Color()
        {
            System.out.println("Constructor called for : " + this.toString());
        }
        public void colorInfo()
        {
            System.out.println("Universal Color");
        }
    }
    

Package

To better organize classes, Java provides a package mechanism to distinguish namespaces for class names.

The three functions of a package are as follows

  1. Distinguish classes with the same name.

  2. A large number of classes can be well managed.

  3. Control access.

Definition

 ```java

Package package name;
```
The rules for naming Java packages are as follows:

  • Package names are all lowercase (multiple words are all lowercase).
  • If the package name contains multiple levels, each level is split by'..
  • Package names usually start with inverted domain names, such as com.baidu, without www.
  • Custom packages cannot start with java

Package Import

\\If you use other classes in different packages, you need to use the full name of the class (package name)+Class name)
    example.Test test = new example.Test();
\\import Package Name+Class name;
import example.Test;\\or
import example.*;

System Package

packageExplain
java.langThe core class library for Java, which contains system classes essential to running Java programs, such as basic data types, basic mathematical functions, string handling, exception handling, and thread classes. The system loads this package by default
java.ioStandard input/output class libraries for the Java language, such as basic input/output streams, file input/output, filter input/output streams, and so on
java.utilContains Date classes such as processing time, Vector classes that handle dynamic arrays, and Stack and HashTable classes
java.awtBuild class libraries for graphical user interfaces (GUIs), Graphics classes for low-level drawing operations, GUI components and layout management (such as Checkbox classes, Container classes, LayoutManger interfaces, etc.), as well as user interface interaction control and event response (such as Event classes)
java.awt.imageJava Tool Class Library for Processing and Manipulating Pictures from the Web
java.wat.peerRarely used directly in programs, making the same Java program run on different hardware and software platforms
java.netClass libraries that implement network functions are Socket class, ServerSocket class
java.lang.reflectProvides tools for reflecting objects
java.util.zipImplement file compression
java.awt.datatransferTool classes for data transfer, including clipboard, string transmitter, and so on
java.sqlClass Libraries Implementing JDBC
java.rmiProvide support for remote connections and loading
java. securityProvide security-related support

9. Exception handling

Concepts of exception handling

A mechanism in a programming language or computer hardware that handles exceptions in software or information systems (that is, certain special conditions that go beyond the normal execution of a program).

Keyword

Several keywords used by the Java exception mechanism: try, catch, finally, throw, throws.

Try - For listening.The code to be listened for (code that may throw an exception) is placed inside the try statement block, and an exception occurs inside the try statement block
The exception is thrown.
Catch - is used to catch exceptions.Catch is used to catch exceptions that occur in a try statement block.
finally - final statement blocks are always executed.It is mainly used to recycle physical resources (such as database connections, networks) that are opened in a try block
Connection and disk files).Only the final block, after execution is complete, will return to execute the return or throw language in the try or catch block
Sentence, if a return or throw termination method statement is used in finally, execution is not jumped back, and execution is stopped directly.
Throw - Used to throw exceptions.
throws - Used in method signatures to declare exceptions that the method may throw.

 try{
        Possible exceptions
    }catch(Exception Type Exception Name(variable)){
        Code to handle exceptions
    }catch(Exception Type Exception Name(variable)){
        Code to handle exceptions
    }...
    [finally{
        Release resource code;
    }]

Differences between Error and Exception

Error is an error in the system. Programmers cannot change or handle it. Errors occur during program compilation and can only be corrected by modifying the program.Generally refers to problems related to virtual machines, such as system crashes, virtual machine errors, insufficient memory, method call stack overflow, and so on.For application interruptions caused by such errors, the program itself cannot recover and prevent them. In the event of such errors, it is recommended that the program be terminated.
Exception indicates an exception that the program can handle, which can be caught and possibly recovered.When such exceptions are encountered, they should be handled as far as possible so that the program can resume running and not terminate at will.

The difference between throw and throws

throw: refers to artificially throwing an exception object in a method (the exception object may have been instantiated by itself or thrown that already exists);
throw ThrowableInstance;
throws: Used on the declaration of a method to indicate that the method must handle exceptions when called.
throw new NullPointerException("demo");

Java Exception Hierarchy Diagram (available online)

10. Collection Framework

All collection classes are located under the java.util package.Java collection classes are mainly derived from two interfaces: Collection and Map, which are the root interfaces of the Java collection framework and contain subinterfaces or implementation classes.

The collection framework is designed to meet the following objectives:

  • The framework must be high performance.The implementation of basic collections (dynamic arrays, chained lists, trees, hash tables) must also be efficient.
  • The framework allows different types of collections to work in a similar manner and is highly interoperable.
  • Extension and adaptation to a set must be simple.

Collection frameworks contain the following:

  • ** Interface: ** is an abstract data type representing a collection.For example, Collection, List, Set, Map, and so on.Multiple interfaces are defined to operate on collection objects in different ways

  • **Implementation (Class): ** is a concrete implementation of the collection interface.Essentially, they are reusable data structures, such as ArrayList, LinkedList, HashSet, HashMap.

  • **Algorithms:**are useful calculations performed by methods within objects that implement a collection interface, such as search and sorting.These algorithms are called polymorphisms because the same methods can be implemented differently on similar interfaces.

Collection is a basic collection interface that can hold a set of collection elements

Collection interface

Collection is the most basic collection interface. A Collection represents a set of Object s, the elements of a Collection. Java does not provide classes that directly inherit from a Collection, but only subinterfaces (such as List s and sets) that inherit from it.

List

The List interface is an ordered, repeatable Collection with precise control over where each element is inserted. The elements in the List can be accessed by an index (where the element is in the List, similar to the subscript of an array). The index of the first element is 0, and the same elements are allowed.

  1. ArrayList

The underlying data structure is an array, which is fast to change and slow to increase or decrease.

Non-threaded security, high efficiency

Method:

sort

import java.util.Collections;  // Introducing Collections class
Collections.sort(sites); *// Alphabetical Sorting*
  1. Vector

The underlying data structure is an array, which is fast to change and slow to increase or decrease.

Thread-safe and inefficient

  1. LinkedList

The underlying data structure is a chain table, which is slow to look up and fast to add or delete.

Non-threaded security, high efficiency

LinkedList is used in the following cases:

  • You need to iterate through a loop to access some elements in the list.
  • Frequent additions and deletions of elements are required at the beginning, middle, and end of the list.

LinkedList inherits the AbstractSequentialList class.

LinkedList implements the Queue interface and can be used as a queue.

LinkedList implements the List interface, which allows listing related operations.

LinkedList implements the Deque ue interface and can be used as a queue.

LinkedList implements the Cloneable interface, which implements cloning.

LinkedList implements the java.io.Serializable interface, which supports serialization and can be transmitted through serialization.

Method:

Set

The Set interface stores a set of unique, disordered objects.

  1. HashSet

The underlying data structure is a hash table. (Unordered**, Unique**)

Depends on two methods: hashCode() and equals() to guarantee element uniqueness

// Introduce HashSet class      
import java.util.HashSet;

public class RunoobTest {
    public static void main(String[] args) {
    HashSet<String> sites = new HashSet<String>();
        sites.add("Google");
        sites.add("Runoob");
        sites.add("Taobao");
        sites.add("Zhihu");
        sites.add("Runoob");  // Duplicate elements will not be added
        System.out.println(sites);
    }
}

Only one Runoob will be output from the above code.

  1. LinkedHashSet

The underlying data structure is a chain table and a hash table. (FIFO insert ordered, unique)

1. Keeping elements in order from a list of chains

2. Keep elements unique by hash table

  1. TreeSet

The underlying data structure is a red-black tree. (Unique, Ordered)

How do I ensure that elements are sorted?Natural Sort, Comparator Sort

Differences between Set and List

  • Set interface instances store unordered, non-duplicated data.List interface instances store ordered, repeatable elements.
  • Set retrieval is inefficient, deletion and insertion are efficient, and insertion and deletion do not change the location of elements <Implementation classes have HashSet, TreeSet>.
  • Lists, like arrays, can grow dynamically, automatically increasing the length of a List based on the length of the data actually stored.Finding elements is efficient and inserting and deleting is inefficient because it causes other element locations to change <The implementation classes are ArrayList, LinkedList, Vector>.

Map is in parallel with Collection.Map provides a key-to-value mapping.A Map cannot contain the same keys, and each key can only map one value.

  1. HashMap

Unordered, non-threaded, safe and efficient.HashMap allows null values (both key and value allow).

  1. HashTable

Unordered, thread-safe, inefficient.With the exception of the constructor, all public method declarations for HashTable have the synchronized keyword, while HashMap's source code does not.HashTable does not allow null values (both key and value allow).

  1. TreeMap

Ordered, non-threaded, safe and efficient (O(logN), but not as efficient as HashMap (O (1).

11. Stream, File, and IO

The Java.io package defines multiple stream types (classes or abstract classes) to implement input/output functionality;

They can be divided from different angles
Class:
1. Data streams can be divided into input streams (InputStream, Reader) and output streams (OutPutStream, Writer)
2. It can be divided into Byte streams (one Byte is 8 bit s) and character streams (one character is 2 bytes) according to the unit of processing data.
3. Node flow and process flow can be divided according to their functions

4. According to the object of operation

InputStream and OutputStream

import java.io.*;
 
public class fileStreamTest {
    public static void main(String[] args) {
        try {
            byte bWrite[] = { 11, 21, 3, 40, 5 };
            OutputStream os = new FileOutputStream("test.txt");
            for (int x = 0; x < bWrite.length; x++) {
                os.write(bWrite[x]); // writes the bytes
            }
            os.close();
 
            InputStream is = new FileInputStream("test.txt");
            int size = is.available();
 
            for (int i = 0; i < size; i++) {
                System.out.print((char) is.read() + "  ");
            }
            is.close();
        } catch (IOException e) {
            System.out.print("Exception");
        }
    }
}

The program above first creates the file test.txt, writes the given number into the file in binary form, and outputs it to the console.

Since the above code is binary, there may be some garbage, you can use the following code examples to solve the garbage problem:

//File name: fileStreamTest2.java
import java.io.*;
 
public class fileStreamTest2 {
    public static void main(String[] args) throws IOException {
        File f = new File("a.txt");
        FileOutputStream fop = new FileOutputStream(f);
        // Build FileOutputStream object, file does not exist will be automatically created
        OutputStreamWriter writer = new OutputStreamWriter(fop, "UTF-8");
        // Build the OutputStreamWriter object, parameters can specify the encoding, default is the operating system default encoding, gbk on windows
        writer.append("Chinese Input");
        // Write to Buffer
        writer.append("\r\n");
        // Line Break
        writer.append("English");
        // Refresh cache flush, write to file, direct close will also write if nothing is written below
        writer.close();
        // Close the write stream and write the buffer contents to a file, so comment out the above
        fop.close();
        // Close Output Stream, Release System Resources
        FileInputStream fip = new FileInputStream(f);
        // Build FileInputStream object
        InputStreamReader reader = new InputStreamReader(fip, "UTF-8");
        // Build the InputStreamReader object with the same encoding as writing
        StringBuffer sb = new StringBuffer();
        while (reader.ready()) {
            sb.append((char) reader.read());
            // Convert to char and add to StringBuffer object
        }
        System.out.println(sb.toString());
        reader.close();
        // Close Read Stream
        fip.close();
        // Close input stream, release system resources
 
    }
}

Reader Stream and Writer Stream

Reader, Write and InputStream, OutputStream: The only difference is that the data units read are (16bit), (8bit)

Create a read directory:

import java.io.File;
 
public class CreateDir {
    public static void main(String[] args) {
        String dirname = "/tmp/user/java/bin";
        File d = new File(dirname);
        // Now create the directory
        d.mkdirs();
    }
}
import java.io.File;
 
public class DirList {
    public static void main(String args[]) {
        String dirname = "/tmp";
        File f1 = new File(dirname);
        if (f1.isDirectory()) {
            System.out.println("Catalog " + dirname);
            String s[] = f1.list();
            for (int i = 0; i < s.length; i++) {
                File f = new File(dirname + "/" + s[i]);
                if (f.isDirectory()) {
                    System.out.println(s[i] + " Is a directory");
                } else {
                    System.out.println(s[i] + " Is a file");
                }
            }
        } else {
            System.out.println(dirname + " Not a directory");
        }
    }
}

delete

import java.io.File;
 
public class DeleteFileDemo {
    public static void main(String[] args) {
        // Modify this to your own test catalog
        File folder = new File("/tmp/java/");
        deleteFolder(folder);
    }
 
    // Delete files and directories
    public static void deleteFolder(File folder) {
        File[] files = folder.listFiles();
        if (files != null) {
            for (File f : files) {
                if (f.isDirectory()) {
                    deleteFolder(f);
                } else {
                    f.delete();
                }
            }
        }
        folder.delete();
    }
}

Cache Stream

Is one of the processing streams, it is to "socket" on the corresponding node stream, provide buffer function for read and write data, avoid frequent read and write hard disk, improve read and write efficiency.New methods have also been added.

BufferedReader(Reader in)
BufferedReader(Reader in,int sz) //sz is the size of the custom buffer
BufferedWriter(Writer out)
BufferedWriter(Writer out,int sz)
BufferedInputStream(InputStream in)
BufferedInputStream(InputStream in,int size)
BufferedOutputStream(InputStream in)
BufferedOutputStream(InputStream in,int size)

BufferedInputStream

package com.kuang.chapter;
import java.io.*;
public class TestBufferStream {
public static void main(String args[]) {
FileInputStream fis = null;
File f = new File("a.txt");
try {
fis = new FileInputStream( f);
// Socket a processing stream BufferedInputStream outside the FileInputStream node stream
BufferedInputStream bis = new BufferedInputStream(fis);
int c = 0;
System.out.println((char) bis.read());
System.out.println((char) bis.read());
bis.mark(100);// Make a mark at the 100th character
for (int i = 0; i <= 10 && (c = bis.read()) != -1; i++) {
System.out.print((char) c);
}
System.out.println();
bis.reset();// Return to the original marker
for (int i = 0; i <= 10 && (c = bis.read()) != -1; i++) {
System.out.print((char) c);
}
bis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e1) {
e1.printStackTrace();
}
}
}

BufferedReader

package com.kuang.chapter;
import java.io.*;
public class TestBufferStream{
public static void main(String args[]){
try{
BufferedWriter bw = new BufferedWriter(new FileWriter("a\\Student.txt"));
//Set another layer of processing stream BufferedWriter outside the node stream FileWriter
String s = null;
for(int i=0;i<100;i++){
s = String.valueOf(Math.random());//"Math.random()" will produce a series of random numbers between 0 and 1.
// The static String valueOf(double d) method of valueOf() serves to
 One double Number of types converted to string
//valueOf() is a static method, so it can be called as a type. static method name
bw.write(s);//Writes a random number string to a specified file
bw.newLine();//Calling the newLine() method causes a line break for each random number written
}
bw.flush();//Call flush() method to empty buffer
BufferedReader br = new BufferedReader(new FileReader("a:\\Student.txt"));
//A further layer of processing stream BufferedReader outside the node stream FileReader
while((s = br.readLine())!=null){
//Reading data from a file using the String readLine() method provided in the BufferedReader processing stream is read line by line
//The condition for the end of the loop is that the table is read with the readLine() method and returns a null string
 Indicates that the end of the file has been read.
System.out.println(s);
}
bw.close();
br.close();
}catch(Exception e){
e.printStackTrace();
}
}
}

Conversion Flow

InputStreamReader and OutputStreamWriter for converting byte data to character data
InputStreamReader needs to "socket" with InputStream.
OutputStreamWriter needs to "socket" with OutputStream.
Conversion streams can specify their encoding set when constructed

import java.io.*;
public class TestTransform1 {
public static void main(String args[]) {
try {
    OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("D:/char.txt"));
    osw.write("Bear Square Garden is annoying");// Writes a string to a specified file
    System.out.println(osw.getEncoding());// Get the default character encoding for the current system using the getEncoding() method
    osw.close();
    osw = new OutputStreamWriter(new FileOutputStream("D:\\java\\char.txt", true), "utf-8");// If true is not added when calling the construction method of FileOutputStream, the newly added string replaces the previously written string, specifying the character encoding when calling the construction method
    osw.write("I don't want to talk to her");// Writes a string to the specified file again, adding the newly written string to the back of the original string
    System.out.println(osw.getEncoding());
    osw.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

data stream

Data Flow DataInputStream DataOutputStream (inherited from InputStream and OutputStream, respectively) - Provides methods for writing basic data types to files or reading them out. Provides access to machine-independent Java raw type data (int, double, and so on).

public static void main(String args[]){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
//When a construction method is called, a ByteArray byte array is first created in memory
DataOutputStream dos = new DataOutputStream(baos);
//Cover the output stream with a layer of data flow to handle the number of int, double types
try{
    dos.writeDouble(Math.random());//Write the resulting random number directly to the byte array
    ByteArray in
    dos.writeBoolean(true);//Boolean data is only one byte in memory
    ByteArrayInputStream bais = new
    ByteArrayInputStream(baos.toByteArray());
        System.out.println(bais.available());
    DataInputStream dis = new DataInputStream(bais);
    System.out.println(dis.readDouble());//Read in first, call readDouble() method to read out random numbers written
    System.out.println(dis.readBoolean());//Read it after you have written it in. The order in which it is read cannot be changed, otherwise the incorrect results will be printed.
    dos.close();
    bais.close();
}catch(Exception e){
e.printStackTrace();
}
}

Print Stream

Print streams are the most convenient class for outputting information. Note that they contain a byte print stream, PrintStream, and a character print stream: PrintWriter.Print streams provide very convenient printing functions.
You can print any type of data information, such as decimals, integers, strings.

Object Flow

The purpose of an object's input-output stream: to write information about the object and to read information about the object.Make the object persistent.
ObjectInputStream: Object input stream
ObjectOutPutStream: Object output stream

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

//Creating a class to write to disk requires implementing the Serializable interface
class Student implements Serializable{
    // This guarantees the uniqueness of the serialVersionUID and prevents the temporary change of attribute variables, which makes the write id different from the read id
    private static final long serialVersionUID = 1L;
    int id ; //Additional need to add an attribute
    String name ;
    transient String sex; //transient modifiers the property, indicating that it is temporary and will not be written to disk
    transient int age;
    public Student(String name,String sex,int age){
        this.name = name;
        this.sex = sex;
        this.age = age;
    }
}

public class objectIO {

    /**
     * @param args
     * @throws IOException
     * @throws ClassNotFoundException
     */
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        // TODO Auto-generated method stub

        createObj();
        readObj();
    }
    //(1) Write the object first
    public static void createObj() throws IOException {
        //1. Create Target Path
        File file = new File("C:\\Users\\bg\\Desktop\\objTest.txt");
        //2. Create circulation channels
        FileOutputStream fos = new FileOutputStream(file);
        //3. Create object output stream
        ObjectOutputStream objOP = new ObjectOutputStream(fos);
        //4. Create class objects and initialize them
        Student stu = new Student("Marisso", "male", 18);
        //5. Write objects to the destination path file
        objOP.writeObject(stu);
        //6. Close resources
        objOP.close();
    }
    //Reread Object
    public static void readObj() throws IOException, ClassNotFoundException {
        File file = new File("C:\\Users\\bg\\Desktop\\objTest.txt");
        FileInputStream fis = new FileInputStream(file);
        ObjectInputStream objIP = new ObjectInputStream(fis);
        //Reading object data requires casting the object stream to the type of object to be written to
        Student stu = (Student)objIP.readObject();
        System.out.println("\n name:"+stu.name+"\n sex:"+stu.sex+"\n age:"+stu.age);
        objIP.close();
    }
}

Closing order of streams

  1. Generally speaking, first open then close, then open and close first
  2. Another scenario: Looking at dependencies, if stream a depends on stream b, you should close stream a first, then stream B.For example, processing flow a depends on node flow b, which should be closed first, then node flow B
  3. Processing streams can be closed without closing node streams.When a processing stream is closed, the closing method of the node stream it is processing is invoked.

12. Multithreading

Processes and Threads

Thread Creation

Inherit Thread class, implement Runnable interface, implement Callable interface

1. Inherit the Thread class

public class ThreadCreateDemo1 {
    public static void main(String[] args) {
        MyThread thread = new MyThread();
        thread.start(); //Call the start() method to start the thread, the thread does not necessarily execute immediately, the CPU schedules the dispatch
    }
}
class MyThread extends Thread {//Inherit Thread Class
    @Override
    public void run() {//Override the run() method to write a thread executor
        super.run();
        System.out.println("hellow_world!");
    }
}

2. Implement Runnable Interface

public class ThreadCreateDemo2 {
    //Create a thread object and call the start() method to start the thread
    public static void main(String[] args) {
        Runnable runnable = new MyRunnable();
        Thread thread = new Thread(runnable);
        thread.start();
    }
}
class MyRunnable implements Runnable {
    public void run() {
        System.out.println("adopt Runnable Threads created!");
    }
}

These two ways of creating work are the same in nature.However, it is recommended to use *** to implement the Runable interface ***.Resolve the limitations of single inheritance.

3. Implement Callable Interface

public class ThreadCreateDemo3 implements Callable<Integer>{
    // Implement the call method as a thread executor
    public Integer call(){
        int i = 0;
        for ( ; i < 100 ; i++ ){
            System.out.println(Thread.currentThread().getName()+ "\t" + i);
        }
        // The call() method may have a return value
        return i;
    }
    public static void main(String[] args) {
        // Create Callable Object
        ThreadCreateDemo3 myCallableTest = new ThreadCreateDemo3();
        // Use FutureTask to wrap Callable objects
        FutureTask<Integer> task = new FutureTask<Integer>(myCallableTest);
        for (int i = 0 ; i < 100 ; i++){
            System.out.println(Thread.currentThread().getName()+ " \t" + i);
            if (i == 20){
                // Essentially, create and start threads as Callable objects
                new Thread(task , "callable").start();
            }
        }
        try{
            // Get Thread Return Value
            System.out.println("callable Return value:" + task.get());
        }
        catch (Exception ex){
            ex.printStackTrace();
        }
    }
}
  1. To implement the Callable interface, a return value type is required

  2. Override call method, need to throw exception

  3. Create Target Object

  4. Create an execution service: ExecutorService ser = Executors.newFixedThreadPool(1);

  5. Commit execution: Future result1 = ser.submit(t1);

  6. Get the result: boolean r1 = result1.get()

  7. Shut down service: ser.shutdownNow();
    summary

  8. However, the implementation of the Runnable interface is basically the same as that of the Callable interface, except that the method defined in the Callable interface has a return value and can declare that an exception was thrown.Therefore, implementing the Runnable interface and implementing the Callable interface can be categorized as one way.

  9. The Runnable, Callable interface creates multithreads, so it's ideal for multiple identical threads to handle the same resource. If you need to access the current thread, you must use the Thread.currentThread() method

  10. Create multithreads by inheriting the Thread class, because the Thread class already inherits the Thread class, it can no longer inherit other parent classes

life cycle

When a thread is created and started, it is neither in the execution state as soon as it starts, nor is it always in the execution state New, Runnable, Running, Blocked, and Dead States


Thread.State:

  1. Initial (NEW): A new thread object has been created, but the start() method has not yet been called.

  2. Run (RUNNABLE): The two general states of ready and running in a Java thread are called run.
    After the thread object is created, other threads, such as the main thread, call the start() method of the object.Threads in this state are in the pool of runnable threads, waiting to be selected by the thread dispatch to gain access to the CPU, and are ready.Threads in a ready state become running after obtaining a CPU time slice.

  3. BLOCKED: Indicates that a thread is blocking on a lock.

  4. Waiting (WAITING): Threads entering this state need to wait for other threads to do some specific action (notification or interruption).

  5. Timeout Wait (TIMED_WAITING: This state is different from WAITING, it can return by itself after a specified time.

  6. Terminate (TERMINATED): Indicates that the thread has finished executing

thread priority

Java provides a thread dispatcher to monitor all threads in the program that are ready to start
The executor determines which thread should be scheduled to execute according to priority.
Threads have a numeric priority ranging from 1 to 10.
hread.MIN_PRIORITY = 1;
Thread.MAX_PRIORITY = 10;
Thread.NORM_PRIORITY = 5;
Change or get priority by
getPriority() . setPriority(int xxx)

Thread method

1public void start() causes the thread to start execution;The Java virtual machine invokes the thread's run method.
2public void run() If the thread is constructed using a separate Runnable run object, the run method of the Runnable object is called;Otherwise, the method does nothing and returns.
3public final void setName(String name) changes the thread name to be the same as the parameter name.
4public final void setPriority(int priority) changes the priority of a thread.
5public final void setDaemon(boolean on) marks the thread as a daemon or user thread.
6The maximum time a public final void join(long millisec) waits for the thread to terminate is millis milliseconds.
7public void interrupt() interrupts the thread.
8public final boolean isAlive() tests whether the thread is active.
9public static void yield() thread comity: suspends the currently executing thread object and executes other threads.
10public static void sleep(long millisec) thread sleep: Sleeps (suspends execution) the currently executing thread for a specified number of milliseconds, which is affected by the accuracy and accuracy of the system timer and scheduler.
11public static boolean holdsLock(Object x) returns true if and only if the current thread holds monitor locks on the specified object.
12Public static Thread current Thread() returns a reference to the currently executing thread object.
13public static void dumpStack() prints the stack trace of the current thread to the standard error stream.

Stop Thread: jdk provides stop, but it is not recommended that you stop it yourself

Daemon thread

Threads are divided into foreground and background threads (user and daemon threads)
Virtual machines must ensure that user threads are executed
The virtual machine does not have to wait for the daemon thread to finish executing

Concurrency, Queues and Locks, Deadlocks

Concurrency is when the same object is operated on simultaneously by multiple threads.

Threads access the same object and some threads want to modify it. Thread synchronization is what we need at this point. Thread synchronization is a wait mechanism in which multiple threads that need to access this object at the same time enter the waiting pool of this object to form a queue, waiting for the previous thread to finish using it and the next line
Check reuse.

The above concurrency problems will be solved by adding a synchronized lock.Don't come in when I lock the door.But with locks, the following will happen:

  1. A thread holding a lock causes all other threads that need it to hang;

  2. Under multithreaded competition, locking and unlocking can cause more context switching and scheduling delays, causing performance problems.

  3. If a higher priority thread waits for a lower priority thread to release the lock, the priority will be inverted, causing performance problems.

    Four prerequisites for a java deadlock to occur:

  • 1. Mutual exclusive use, i.e. when a resource is used (occupied) by one thread, it cannot be used by another thread

  • 2. It is not preemptive, and the resource requester cannot force the resource to be seized from the resource holder. The resource can only be released by the resource holder on its own initiative.

  • 3. Request and hold, that is, when a resource requester requests other resources, he or she keeps possession of the original resources.

  • 4. Circular waiting, that is, there is a waiting queue: P1 occupies the resources of P2, P2 occupies the resources of P3, and P3 occupies the resources of P1.This creates a waiting loop.

    In case of deadlock, breaking any of the above conditions will make the deadlock disappear.

import java.util.Date;
 
public class LockTest {
   public static String obj1 = "obj1";
   public static String obj2 = "obj2";
   public static void main(String[] args) {
      LockA la = new LockA();
      new Thread(la).start();
      LockB lb = new LockB();
      new Thread(lb).start();
   }
}
class LockA implements Runnable{
   public void run() {
      try {
         System.out.println(new Date().toString() + " LockA Start execution");
         while(true){
            synchronized (LockTest.obj1) {
               System.out.println(new Date().toString() + " LockA Lock up obj1");
               Thread.sleep(3000); // Waiting here is to give B the chance to lock in
               synchronized (LockTest.obj2) {
                  System.out.println(new Date().toString() + " LockA Lock up obj2");
                  Thread.sleep(60 * 1000); // For testing, don't leave it occupied
               }
            }
         }
      } catch (Exception e) {
         e.printStackTrace();
      }
   }
}
class LockB implements Runnable{
   public void run() {
      try {
         System.out.println(new Date().toString() + " LockB Start execution");
         while(true){
            synchronized (LockTest.obj2) {
               System.out.println(new Date().toString() + " LockB Lock up obj2");
               Thread.sleep(3000); // Waiting here is to give A the chance to lock in
               synchronized (LockTest.obj1) {
                  System.out.println(new Date().toString() + " LockB Lock up obj1");
                  Thread.sleep(60 * 1000); // For testing, don't leave it occupied
               }
            }
         }
      } catch (Exception e) {
         e.printStackTrace();
      }
   }
}

Result

Tue May 05 10:51:06 CST 2015 LockB Start execution
Tue May 05 10:51:06 CST 2015 LockA Start execution
Tue May 05 10:51:06 CST 2015 LockB Lock up obj2
Tue May 05 10:51:06 CST 2015 LockA Lock up obj1

Solve

import java.util.Date;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
 
public class UnLockTest {
   public static String obj1 = "obj1";
   public static final Semaphore a1 = new Semaphore(1);
   public static String obj2 = "obj2";
   public static final Semaphore a2 = new Semaphore(1);
 
   public static void main(String[] args) {
      LockAa la = new LockAa();
      new Thread(la).start();
      LockBb lb = new LockBb();
      new Thread(lb).start();
   }
}
class LockAa implements Runnable {
   public void run() {
      try {
         System.out.println(new Date().toString() + " LockA Start execution");
         while (true) {
            if (UnLockTest.a1.tryAcquire(1, TimeUnit.SECONDS)) {
               System.out.println(new Date().toString() + " LockA Lock up obj1");
               if (UnLockTest.a2.tryAcquire(1, TimeUnit.SECONDS)) {
                  System.out.println(new Date().toString() + " LockA Lock up obj2");
                  Thread.sleep(60 * 1000); // do something
               }else{
                  System.out.println(new Date().toString() + "LockA lock obj2 fail");
               }
            }else{
               System.out.println(new Date().toString() + "LockA lock obj1 fail");
            }
            UnLockTest.a1.release(); // release
            UnLockTest.a2.release();
            Thread.sleep(1000); // Try it now. In reality, do something is indeterminate
         }
      } catch (Exception e) {
         e.printStackTrace();
      }
   }
}
class LockBb implements Runnable {
   public void run() {
      try {
         System.out.println(new Date().toString() + " LockB Start execution");
         while (true) {
            if (UnLockTest.a2.tryAcquire(1, TimeUnit.SECONDS)) {
               System.out.println(new Date().toString() + " LockB Lock up obj2");
               if (UnLockTest.a1.tryAcquire(1, TimeUnit.SECONDS)) {
                  System.out.println(new Date().toString() + " LockB Lock up obj1");
                  Thread.sleep(60 * 1000); // do something
               }else{
                  System.out.println(new Date().toString() + "LockB lock obj1 fail");
               }
            }else{
               System.out.println(new Date().toString() + "LockB lock obj2 fail");
            }
            UnLockTest.a1.release(); // release
            UnLockTest.a2.release();
            Thread.sleep(10 * 1000); // This is just for demonstration purposes, so tryAcquire only takes 1 second, and B gives A time to execute, otherwise the two are always deadlocked
         }
      } catch (Exception e) {
         e.printStackTrace();
      }
   }
}
Tue May 05 10:59:13 CST 2015 LockA Start execution
Tue May 05 10:59:13 CST 2015 LockB Start execution
Tue May 05 10:59:13 CST 2015 LockB Lock up obj2
Tue May 05 10:59:13 CST 2015 LockA Lock up obj1
Tue May 05 10:59:14 CST 2015LockB lock obj1 fail
Tue May 05 10:59:14 CST 2015LockA lock obj2 fail
Tue May 05 10:59:15 CST 2015 LockA Lock up obj1
Tue May 05 10:59:15 CST 2015 LockA Lock up obj2
  1. Comparison of synchronized and Lock
    Lock is explicit (manually open and close locks, don't forget to close locks) synchronized is implicit and automatically released from scope
  2. Lock only has code block locks, synchronized has code block locks and method locks using Lock locks, and JVM will spend less time dispatching threads for better performance.And has better scalability (provides more subclasses)
  3. Priority:
    Lock > Synchronize Code Block (already in the method body, allocated resources) > Synchronize Method (at party
    Beyond the body of law)

Thread Communication

The goal of thread communication is to enable threads to signal each other.Thread communication, on the other hand, enables threads to wait for signals from other threads.

How threads communicate

  1. volatile
  2. Wait/Notify mechanism
  3. join mode
  4. threadLocal
  5. CountDownLatch Concurrency Tool
  6. CyclicBarrier Concurrency Tool

volatile

public class Volatile implements Runnable {
  private static volatile Boolean flag = true;

  @Override
  public void run() {
    while (flag) {
      System.out.println(Thread.currentThread().getName() + " - implement");
    }
    System.out.println("Thread End");
  }

  public static void main(String[] args) {
    Thread t = new Thread(new Volatile());
    t.start();
    try {
      Thread.sleep(5);
      flag = false;
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }
}
Thread-0 - implement
Thread-0 - implement
Thread-0 - implement
Thread-0 - implement
Thread-0 - implement
 Thread End

**WaitNotify **

public class WaitNotify {
  // State Lock
  private static Object lock = new Object();
  private static Integer i = 0;

  public void odd() {
    while (i < 10) {
      synchronized (lock) {
        if (i % 2 == 1) {
          System.out.println(Thread.currentThread().getName() + " - " + i);
          try {
            Thread.sleep(1000);
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
          i++;
          lock.notify();
        } else {
          try {
            lock.wait();
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
        }
      }
    }
  }

  public void even() {
    while (i < 10) {
      synchronized (lock) {
        if (i % 2 == 0) {
          System.out.println(Thread.currentThread().getName() + " - " + i);
          try {
            Thread.sleep(1000);
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
          i++;
          lock.notify();
        } else {
          try {
            lock.wait();
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
        }
      }
    }
  }

  public static void main(String[] args) {

    WaitNotify waitNotify = new WaitNotify();

    Thread t1 = new Thread(() -> waitNotify.odd(), "Thread 1");
    Thread t2 = new Thread(() -> waitNotify.even(), "Thread 2");

    t1.start();
    t2.start();
  }
}

join

package threadCommunication;
 
public class JoinTest extends Thread {
    @Override
    public void run() {
        try {
            int sleepTime = (int) (Math.random() * 1000);
            System.out.println(sleepTime);
            Thread.sleep(sleepTime);
            System.out.println("JoinTest end");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
 
    public static void main(String[] args) throws InterruptedException {
        JoinTest j = new JoinTest();
        j.start();
        j.join();//The current thread main waits for the thread object (j) to be destroyed
        System.out.println("main end");
    }

threadLocal

package sync; 
public class SequenceNumber { 
 // Define an anonymous subclass to create a ThreadLocal variable 
 private static ThreadLocal<Integer> seqNum = new ThreadLocal<Integer>() { 
 // Override Initialization Method 
 public Integer initialValue() { 
 		return 0; 
 	} 
 }; 
 // Next serial number 
 public int getNextNum() { 
     seqNum.set(seqNum.get() + 1); 
     return seqNum.get(); 
 } 
 private static class TestClient extends Thread { 
     private SequenceNumber sn; 
     public TestClient(SequenceNumber sn) { 
     this.sn = sn; 
 } 
 // Thread Generates Sequence Number 
 public void run() { 
     for (int i = 0; i < 3; i++) { 
         System.out.println("thread[" + Thread.currentThread().getName() + "] sn[" + 			sn.getNextNum() + "]"); 
         } 
 	} 
 } 
 /** 
 * @param args 
 */ 
 public static void main(String[] args) { 
     SequenceNumber sn = new SequenceNumber(); 
     // Three threads produce their own serial numbers 
     TestClient t1 = new TestClient(sn); 
     TestClient t2 = new TestClient(sn); 
     TestClient t3 = new TestClient(sn); 
     t1.start(); 
     t2.start(); 
     t3.start(); 
 } 
}
thread[Thread-1] sn[1] 
thread[Thread-1] sn[2] 
thread[Thread-1] sn[3] 
thread[Thread-2] sn[1] 
thread[Thread-2] sn[2] 
thread[Thread-2] sn[3] 
thread[Thread-0] sn[1]
thread[Thread-0] sn[2] 
thread[Thread-0] sn[3]

**CountDownLatch **CountDownLatch can replace wait/notify and remove synchronized

import java.util.concurrent.CountDownLatch;

public class CountDown {
  private static Integer i = 0;
  final static CountDownLatch countDown = new CountDownLatch(1);

  public void odd() {
    while (i < 10) {
      if (i % 2 == 1) {
        System.out.println(Thread.currentThread().getName() + " - " + i);
        try {
          Thread.sleep(1000);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
        i++;
        countDown.countDown();
      } else {
        try {
          countDown.await();
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
    }
  }

  public void even() {
    while (i < 10) {
      if (i % 2 == 0) {
        System.out.println(Thread.currentThread().getName() + " - " + i);
        try {
          Thread.sleep(1000);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
        i++;
        countDown.countDown();
      } else {
        try {
          countDown.await();
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
    }
  }

  public static void main(String[] args) {

    CountDown countDown = new CountDown();

    Thread t1 = new Thread(() -> countDown.odd(), "Thread 1");
    Thread t2 = new Thread(() -> countDown.even(), "Thread 2");

    t1.start();
    t2.start();
  }
}

CyclicBarrier

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

public class CyclicBarrierTest {
  public static void main(String[] args) {
    CyclicBarrier cyclicBarrier = new CyclicBarrier(3);
    new Thread(() -> {
      System.out.println(Thread.currentThread().getName() + ": Get ready...");
      try {
        cyclicBarrier.await();
      } catch (InterruptedException e) {
        e.printStackTrace();
      } catch (BrokenBarrierException e) {
        e.printStackTrace();
      }
      System.out.println("Finished Starting All!");
    }, "Thread 1").start();

    new Thread(() -> {
      System.out.println(Thread.currentThread().getName() + ": Get ready...");
      try {
        cyclicBarrier.await();
      } catch (InterruptedException e) {
        e.printStackTrace();
      } catch (BrokenBarrierException e) {
        e.printStackTrace();
      }
      System.out.println("Finished Starting All!");
    }, "Thread 2").start();

    new Thread(() -> {
      System.out.println(Thread.currentThread().getName() + ": Get ready...");
      try {
        cyclicBarrier.await();
      } catch (InterruptedException e) {
        e.printStackTrace();
      } catch (BrokenBarrierException e) {
        e.printStackTrace();
      }
      System.out.println("Finished Starting All!");
    }, "Thread 3").start();
  }
}
Thread 3: Get ready...
Thread 2: Get ready...
Thread 1: Get ready...
Finished Starting All!
Finished Starting All!
Finished Starting All!

Thread Pool

Often created and destroyed, particularly intensive resources, such as threads in concurrent situations, can have a significant impact on performance.Create many threads in advance, put them in the thread pool, get them directly when using them, and put them back into the pool when using them.Frequent creation of destruction and reuse can be avoided.

ExecutorService and Executors

  1. **ExecutorService:**True thread pool interface.Common Subclass ThreadPoolExecutor
    void execute(Runnable command): Executes a task/command, does not return a value, is commonly used to enforce
    Row Runnable

  2. Future submit(Callable task): executes a task, has a return value, and generally executes
    Callable

  3. void shutdown(): Close connection pool

**Executors:**Tool class, factory class for thread pools, used to create and return different types of thread pools

13. Notes

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

Effect

It is not the program itself, it can be interpreted. (This is no different from comment)

It can be read by other programs such as compilers.

It can be attached to packages, classes, methods, fields, etc., which adds extra helpful information to them

We can access these metadata through a reflection mechanism

format

Annotations exist in the code as'@Annotation Name'

You can also add parameter values such as: @SuppressWarnings(value="unchecked")

Built-in Notes


Java defines a set of 10 annotations, the first three in java.lang, the fourth in java.lang.annotation, and the next three

Comments for Code( java.lang )yes
@Override - Check if this method is an override.Compilation errors are reported if the method is not found in its parent class or in the referenced interface.
@Deprecated - Mark out-of-date methods.If this method is used, a compilation warning will be reported.
@SuppressWarnings - Instructs the compiler to ignore warnings declared in comments.
Notes to be used in other notes(Or meta-notes)yes( java.lang.annotation)annotation
@Retention - Identify how this comment is saved, whether it's in code only, or in code class Files, or at run time, can be accessed through reflection.
@Documented - Mark whether these comments are included in user documentation.
@Target - Mark what this comment should be Java Members.
@Inherited - Mark which annotation class this annotation inherits from(Default annotations do not inherit from any subclasses)
java7 Comments added after
@SafeVarargs - Java 7 Begins to support, ignoring any warnings from method or constructor calls that use parameters as generic variables.
@FunctionalInterface - Java 8 Begin support by identifying an anonymous function or functional interface.
@Repeatable - Java 8 Begin support to identify a comment that can be used multiple times on the same declaration.
package com.annotation;
//Test built-in annotations
import java.util.ArrayList;
import java.util.List;
//All classes inherit Object classes by default
public class Test1 extends Object {
    //@Override representation override
    //-->View JDK Help Documentation
    //-->Test the effects of different names
    @Override
    public String toString() {
    	return super.toString();
    }
     //The method is out of date, not recommended to use, may have problems, not can not be used!
    //-->View JDK Help Documentation
    @Deprecated
    public static void stop(){
    	System.out.println("test @Deprecated");
    }
    //@SuppressWarnings suppresses warnings and can pass parameters
    //-->View JDK Help Documentation
    //Look at the source code: Discovering parameter types and parameter names is not a method!
    @SuppressWarnings("all")
    public void sw(){
   	 List list = new ArrayList();
    }
    public static void main(String[] args) {
   	 stop();
    }
}   

meta annotation

package com.annotation;
import java.lang.annotation.*;
//Test Meta Comment
public class Test2 {
@MyAnnotation
public void test(){
}
}
//Define a comment
@Target(value = {ElementType.METHOD,ElementType.TYPE})
@Retention(value = RetentionPolicy.RUNTIME)
@Inherited
@Documented
@interface MyAnnotation{
}

Custom Notes

  1. When using @interface to customize annotations, the java.lang.annotation.Annotation interface is automatically inherited
    @ interface is used to declare a comment in the format: public @ interface comment name {Define Content}

  2. Each of these methods actually declares a configuration parameter.
    The name of the method is the name of the parameter.

  3. The return value type is the type of the parameter (return values can only be basic types, Class, String, enum).
    Default values of parameters can be declared by default

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

  5. Annotation elements must have values. When we define annotation elements, we often use an empty string with 0 as the default value.

Supportable data types for annotation parameters:
1. All basic data types (int,float,boolean,byte,double,char,long,short)
2.String type
3.Class type
4.enum type
5.Annotation type
6. Arrays of all types above

package annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Fruit Name Notes
 * @author peida
 *
 */
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface FruitName {
    String value() default "";
}
package annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Fruit color notes
 * @author peida
 *
 */
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface FruitColor {
    /**
     * Color Enumeration
     * @author peida
     *
     */
    public enum Color{ BULE,RED,GREEN};
    
    /**
     * Color property
     * @return
     */
    Color fruitColor() default Color.GREEN;

}
package annotation;

import annotation.FruitColor.Color;

public class Apple {
    
    @FruitName("Apple")
    private String appleName;
    
    @FruitColor(fruitColor=Color.RED)
    private String appleColor;
    
    
    
    
    public void setAppleColor(String appleColor) {
        this.appleColor = appleColor;
    }
    public String getAppleColor() {
        return appleColor;
    }
    
    
    public void setAppleName(String appleName) {
        this.appleName = appleName;
    }
    public String getAppleName() {
        return appleName;
    }
    
    public void displayName(){
        System.out.println("The name of the fruit is: apple");
    }
}

//Set Default Value
package annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Notes for fruit suppliers
 * @author peida
 *
 */
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface FruitProvider {
    /**
     * Vendor number
     * @return
     */
    public int id() default -1;

    /**
     * Vendor Name
     * @return
     */
    public String name() default "";

    /**
     * Vendor Address
     * @return
     */
    public String address() default "";
}

14. Reflection

Reflection mechanism

Java's reflection mechanism is implemented through four classes: class, Constructor, Field, Method;
The time class object represented by the class, the constructor object of the Constructor-class, the attribute object of the Field-class, and the method object of the Method-class.These four objects give us a rough look at the components of a class.

Methods to get classes

//Call the.Class property of the runtime class itself
Class clazz = String.class;

//Get by object of runtime class
Person p = new Person();

Class clazz = p.getClass();

//Obtained through Class's static method: reflective dynamics
String className = "java.util.commons";

Class clazz = Class.forName(className);

//Loader through classes
String className = "java.util.commons";

ClassLoader classLoader = this.getClass().getClassLoader();

Class clazz = classLoader.loadClass(className);

How to get the constructor

Constructor getConstructor(Class[] params) -- Gets a public constructor that uses a special parameter type. 
 
Constructor[] getConstructors() -- Get all the common constructors for the class 
 
Constructor getDeclaredConstructor(Class[] params) -- Get a constructor that uses a specific parameter type(Not related to access level) 
 
Constructor[] getDeclaredConstructors() -- Get all constructors for the class(Not related to access level)

Get Fields

Field getField(String name) -- Get named public fields 
 
Field[] getFields() -- Get all the public fields of the class 
 
Field getDeclaredField(String name) -- Gets the named field of the class declaration 
 
Field[] getDeclaredFields() -- Get all fields of class declaration

Getting information about methods

Method getMethod(String name, Class[] params) -- Get named public methods using specific parameter types 
 
Method[] getMethods() -- Get all the public methods of a class 
 
Method getDeclaredMethod(String name, Class[] params) -- Using close-up parameter types to get a named method for class declarations 
 
Method[] getDeclaredMethods() -- All methods for obtaining class declarations

Get member variables, member methods, interfaces, superclasses, construction methods, etc. through the Class class

package com.ys.reflex;
public class Person {
    //Private Properties
    private String name = "Tom";
    //Public Property
    public int age = 18;
    //Construction method
    public Person() {
    }
    //Private Method
    private void say(){
        System.out.println("private say()...");
    }
    //public Method
    public void work(){
        System.out.println("public work()...");
    }
}
//Get the full name of the class
String className = c2.getName();
System.out.println(className);//Output com.ys.reflex.Person

//Gets the properties of the class's public type.
Field[] fields = c2.getFields();
for(Field field : fields){
   System.out.println(field.getName());//age
}

//Gets all the properties of the class.Including Private
Field [] allFields = c2.getDeclaredFields();
for(Field field : allFields){
    System.out.println(field.getName());//name    age
}

//A method to get the public type of a class.Some methods of the Object class are included here
Method [] methods = c2.getMethods();
for(Method method : methods){
    System.out.println(method.getName());//work waid equls toString hashCode, etc.
}

//Get all methods of the class.
Method [] allMethods = c2.getDeclaredMethods();
for(Method method : allMethods){
    System.out.println(method.getName());//work say
}

//Gets the specified property
Field f1 = c2.getField("age");
System.out.println(f1);
//Gets the specified private property
Field f2 = c2.getDeclaredField("name");
//Enables and disables the access security check switch with a value of true, indicating that the reflected object should cancel the access check in the java language when used;Don't Cancel Conversely
f2.setAccessible(true);
System.out.println(f2);

//Create an object of this class
Object p2 =  c2.newInstance();
//Assign the f2 attribute of the p2 object to Bob, and the f2 attribute is the private attribute name
f2.set(p2,"Bob");
//The use of reflection mechanisms can break encapsulation, resulting in unsafe attributes for java objects.
System.out.println(f2.get(p2)); //Bob

//Get construction methods
Constructor [] constructors = c2.getConstructors();
for(Constructor constructor : constructors){
    System.out.println(constructor.toString());//public com.ys.reflex.Person()
}

Reflection Method Execution

public class Apple {

    private int price;

    public int getPrice() {
        return price;
    }

    public void setPrice(int price) {
        this.price = price;
    }

    public static void main(String[] args) throws Exception{
        //Normal call
        Apple apple = new Apple();
        apple.setPrice(5);
        System.out.println("Apple Price:" + apple.getPrice());
        //Use reflection calls
        Class clz = Class.forName("com.wyl.api.Apple");
        Method setPriceMethod = clz.getMethod("setPrice", int.class);
        Constructor appleConstructor = clz.getConstructor();
        Object appleObj = appleConstructor.newInstance();
        setPriceMethod.invoke(appleObj, 14);
        Method getPriceMethod = clz.getMethod("getPrice");
        System.out.println("Apple Price:" + getPriceMethod.invoke(appleObj));
    }
}

Posted by bur147 on Sat, 04 Sep 2021 10:06:01 -0700