1. Environmental

JDK —- Java Development Kit — Software for Java programmers JRE —- Java Runtime Evironment — Software used by users when running Java SE — Standard edition — Simple Server Java Platform EE — Enterprise Edition — Complex Server Java Platform ME — Micro Edition — Small Server Java Platform SDK —- Software Development Kit — Enterprise Edition — Complex Server Java Platform ME — Micro Edition — Small Server Java Platform SDK —- Software Development Kit — Software development kit

2. Data type

Size 2 to the (x bit -1), plus or minus sign at the beginning

Int 32-bit 4 bytes -2 billion to 2 billion 2^31 short 16 bits 2 bytes -3W to 3W 2^15 long 64-bit 8 bytes Byte 8 bits 1 Byte -128 to 127 float 32-bit 4 bytes 6.7 valid digits Char 16 bits 2 bytes Can hold Chinese characters, such as addition and subtraction, converted to their ASCII counterparts in ints

BigDecimal High precision Large floating point number BigInteger Arbitrary precision integer Add (BigInteger/BigDecimal A) + Subtract (BigInteger/BigDecimal A) – Multiply (BigInteger/BigDecimal A) * divide(BigInteger/BigDecimal a)/mod(BigInteger/BigDecimal a) Square root of remainder SQRT ()

Final – can only be assigned once

<< left shift — example: 1<<3 =8 — 1 left shift 3 — 0000 0001 → 0000 1000 =8

The String used API

1 s.substring(0,3) cut the string from 0 to 3 2 s.qualsignorecase () is case insensitive. 3 char s.charat (1) Returns the first char value: example: Hello.charat (1) = “e” 4 String[] s.split(“,”) “, AsList (s.split(“,”))→ “,” List<> 5 int x.compareTo(String y) returns x-y; X small returns a negative number, and vice versa, String. Length ==0 7 int Length () length 8 String replace(String old,String new) Replace old with new — example: Hello. Replace (“o”,”a”) → hella 9 String trim() 10 int indexOf(String STR,int from) IndexOf (“o”,1) looking for o (e) starting from 1 returns =4

StringBuilder String builder
StringBuilder is used when you want to change strings frequentlyCopy the code
The StringBuilder commonly used API
StringBuilder b=new StringBuilder()
Copy the code

1 StringBuilder AppEnd (String add) add String B.append (“aaa”),b.append(“b”) b=” aaAB “2 StringBuilder Insert (int position,String STR) Add a STR 3 to position StringBuilder delete(int startPosition,int endPosition) Deletes from startPosition to endPosition

An array of
Int [] a=new int[100] int[] a={1,2,3,4}; Sort (a) -- This method uses "optimized quicksort algorithm" Quicksort algorithm: 1. Set a boundary and put the small one on the left and the big one on the right. Set another bounding value in the left heap, and then put the small one on the left and the large one on the right, recursively until the order is sorted.Copy the code
To call arrays.sort () for sorting, you must implement the Comparable interface. Example:main(){
     var staff=new Empoyee()[3];
     staff[0] =new Empoyee("The king".1100);// Name, id
     staff[1] =new Empoyee("Zhang".4500);
     staff[2] =new Empoyee("Li".1200); The Arrays. Sort (staff);// Sort people by ID
   } 
   
   public Empoyee implement Comparable<Empoyee>{  // Normal javaBean + implements the Comparable interface
      String name;
      int id;
      
      public Empoyee(String name,int id){
       this.name=name;
       this.id=id;
      }
      
      public int compare(Empoyee other){  // The method that needs to be implemented in the interface, which returns the comparison value
         //x.compare(y) is x-y,x is positive,x is negative, equals 0
        return Integer.compare(id,other.getId()); // Each wrapper class has its own implementation of this method}}Copy the code
XXX [] Arrays. CopyOf (XXX [] a,int end) XXX [] Arrays. CopyOfRange (XXX [] A,int Start,int end) Int binarySearch(XXX [] a,int Start,int end, XXX v) start,int end, XXX v) Private Static Final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {}; private Static Final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {}; If length+1 is larger than the current array length, expand the array to 10: int newCapacity = oldCapacity + (oldCapacity >> 1); Move one to the right to expand by 1.5 times.Copy the code

3. Objects and classes

Class: A template or blueprint for constructing an object. Encapsulation: Combining data and behavior in a package and hiding the implementation from consumers of the object. Object data = instance field. Method: procedure for manipulating data var weakly typed variable, can only be used for local variables! If the type can be derived from the variable's initial value, it can be declared using var without specifying the type.Copy the code
Relationships between classes

· Rely on uses-a to use, call the English name to know the meaning · aggregate HAS-a to form, inherit IS-A

Final: Such fields must be initialized when the object is constructed and cannot be modified. Static: Each object has a copy, but static modifiers have no copy. This object is common. So static methods don’t use new, they can’t create new copies for everyone.

The method parameters

※※※Java always calls by value, which means that the value of a method parameter is a copy, meaning that a method cannot change the value of a variable passed to it.

Example: int a = 10; add(a); privite void add(int a){ a=3*a; A = 10} result;Copy the code

But object references are different! Method gets a copy of the reference to the object but copy = references refer to the same object and can change the value of the object.

MyInt a=new MyInt(10); add(a); privite void add(MyInt a){ a=3*a; A = 30} result;Copy the code

● Methods cannot modify parameters of basic data types ● methods can change the state of object parameters ● Methods cannot make a parameter reference to a new object

Overloading: Same method name, different input parameter. The process by which the compiler matches which method to call is called overload resolution, where each method has its own method signature. Such as indexOf (int), indexOf (String, int)… But the return value is not part of the signature!

Generate a Random number: a=new Random().nextint (100); Random() Generates a Random number nextInt (int n) Generates a Random number ranging from 0 to n-1

package

Package name: url, in turn, + + the name of the class, such as project name: com. Baidu. Corejava. The Employee a class can use their own package all the classes + other packages with class. Declare the full name or import java.time.*;

The jar file

When you package your application, you only want to provide users with a single file, not a file with lots of classes. Jar files are designed for this purpose. A JAR file can contain class files, images, sounds, and so on. And the JAR is compressed, using the ZIP compression format.

Create jar: The tools are in the JDK /bin directory

annotation

/** @param + Parameter Remarks @return + Returned remarks @throws + Possible exceptions @auther + author @see,link + entry */

Class design techniques

Make sure data is private 2. Make sure data is initialized 3. Don’t use too many base types in your classes — replace similar base classes 4. Not all fields require separate field accessors, changers. 5. Decompose a class with too many responsibilities 6. Class name method names show responsibilities 7

4. Inheritance

Subclass = Derived = Child extends Superclass = Base class = Superclass Inheritance: A subclass can add to, but not delete, its parent. Super is not the same as this reference. Super is not a reference to an object, but just a keyword that can access a superclass method. This is a reference to an object that can be assigned and manipulated.

The subclass constructor cannot access the private fields of the parent class. These private fields must be initialized through a constructor. The superclass constructor can be called using super, and the first sentence is used. If there is no constructor that writes the super display to call the parent class, then the system implicitly calls the parent class with no arguments. Initializing a class (new, etc.) will run the constructor of the class -> parent constructor -> grandparent constructor… All the way to the top of the inheritance tree, and then after running the class at the top and then running the class at the bottom and then running the class at the bottom. ————– so the subclass does not use super, and the superclass does not have a no-argument constructor that will cause an error.

Subclass parent classes have methods of the same name and then call that method automatically matching is polymorphism polymorphism: the phenomenon of an object variable indicating multiple actual types is called polymorphism.

Dynamic binding: Automatically selects the appropriate method at run time. Static binding: the compiler declared by the private/static/final/ constructor can find which overload resolution directly: the method compiler of the same name resolves which to call with arguments

The “IS-A” rule = replacement principle, if two classes can be replaced they should be designed as inheritance. Managers are employees managers inherit employees. Employee e=new Manager(); Square root

Summary method calls: The compiler looks for a specific method by signature (method name and parameter), if it doesn’t look for its parent class, if it doesn’t look for its parent class… But this takes too long, so the virtual machine defines a method table and simply finds the table.

❤❤❤ Prevent inheritance!! Final classes and methods: extension is not allowed. If you don’t want it to be inherited, you use final, final fields, you can’t change the value after initialization. There is an argument that methods that do not have enough reason to use polymorphism should be declared final, and subclasses should be less disruptive, so the system can reduce overhead (inlining: there is only one method, multiple choices are not overridden, and the compiler optimizes directly to run faster).

Cast casting

● Strong can only be done within the inheritance hierarchy ● Strong should be checked with instanceof before strong

If (ee instanceof Mannger) {Mannger a=(Mannger); }Copy the code

● Reduce strong turn, strong turn shows that the design is not reasonable, multi-modal, less strong turn

An abstract class abstract

The ancestors of inheritance trees generally use abstraction rather than concrete implementation. Abstraction is simply defining method names and parameters and letting subclasses implement them.

Private can only be accessed by itself. Public can all be accessed. 3. Protected can only be accessed in the same package. Default + this package

Object

Object is the ancestor of all Java classes. Only primitive types are not objects in Java. The ancestor of objects is Object. All arrays are Objects.

equals

Ojb.equals () — Determines whether references are equal. Equals returns false equals if two are not the same class. Symmetry: x.equials (y)=ture // y.equials (x)=ture 3. Transitivity: x.equials (y)=ture // y.equials (z)=ture // x.equials (z)=ture 4. Consistency: repeatedly calling a result 5.x. als(null) is always false

Equals (a,b) Object Equals (a,b) =true

hashCode

A hash code is an integer value (which can be negative) exported from an object that represents the storage address. Null. HashCode () error!!!!!! Objects.hashCode(null)=0

toString

Custom toString class name+ [“name=”+name+”,”+… The toString of Object is the name of the Object class + hashCode

Class getClass() returns the Class object that contains the object information. String getName() returns the Class name. Class getSuperClass() returns the parent object

ArrayList automatically adjusts the size of an array. When the capacity is full, add automatically creates a larger array and copies objects from the smaller array to the larger array. Or: list.ensurecapacity (100) initially declares an array of size 100. Or new ArrayList < > (100);

List.add (3) —- > Adding an int automatically converts to an Integer –> list.add(integer.valueof (3)) Int a=list.get(I) —- > is automatically converted to Integer –> int a=list.get(I).intValue(); Automatic unpacking, automatic unpacking

Int intValue() Returns int String toString() int paresInt(String s)/(String s,int radix) Integer valueOf(String s)

max(Object… args) –> Object… = Object [] — > Max (three, four, five), the compiler will be parsed into Max (new Object [] {three, four, five})

Enumeration enum

● Enum Size{SMALL,MEDIUM} enumerations generally do not require constructors. If a constructor is required, it must be private and used to initialize assignments. Size[] value=Size.values(); Size s=Enum. ValueOf (Size. Class,”SMALL”) –> s=Size

Enum valueOf(Class Enum,String name) Enumeration constant of name toString Returned constant name int ordinal Returned position int compareTo(E other)

❤ ❤ ❤reflection❤ ❤ ❤

A program that analyzes the capabilities of a class is called reflection. Reflection is a powerful and complex mechanism that can be used to: ● analyze the capabilities of a class at run time ● examine objects at run time, for example: write a toString Method that uses all classes ● implement generic array manipulation code ● utilize Method objects (similar to function Pointers in C++)

Class Class

The Java runtime system always maintains a runtime type identity for all objects while the program is running. This information keeps track of the class to which each object belongs. The virtual machine uses runtime type information to select methods to execute. The name of the Class that holds this information is Class. This Class instance can be accessed through Object’s getClass() method.

①②③ var aaa= new Random(); (1) Class cl = aaa. GetClass (); String name = cl.getName(); // Get the full name with the package name “java.util.random”

Class ②Class c= class.forname (” java.util.random “);

(3) the Class cl = Random. The Class; A class object actually represents a type, either a class or something else, such as int.class

Every Class has a unique Class object if (LLDB etClass()== random.class) that can be passed but a subclass of Random cannot. If (e instanceof Manager) (subclass) can pass

● Get objects by Class. If you have a Class object, you can use it to construct an instance of the Class. Call the getConstructor method to get a Constructor object, and then use the newInstance method to construct an instance. Such as: Class c = Class. Class.forname (” Java. Util. Random “); Object obj=cl.getConstructor().newInstance();

Constructor getConstructor(Class c) generates an object describing the Constructor with the specified parameter type. Object newInstance(Object params) passes params to the constructor to construct a newInstance of the constructor declaration class.

URL getResoure(String name) — class.getResoure(“aaa.txt”) InputStream getResoureAsStream(String name) — Class.getresoureasstream (“aaa.txt”) finds the resource at name and returns the URL or InputStream

❤ Field – (translation) Field | | the Methods – method (translation) | | Constructors – (translation) constructor, the constructor (all) -vice FieId [] the getFields (); FieId[] getDeclaredFields(); Return to classes in all the fields where void AccessibleObject. SetAccessible (FieId [] fieIds, Boolean flag) Set the access permission in batches. ● FieId getFields(String name); FieId getDeclaredFields(String name); FieId getDeclaredFields(String name); Return the Field of name ● void setAccessible(Boolean flag) Set access ● Object get(Object obj) Returns the value of the Field described by the Field Object in the obJ Object ● Object Set (Object obj,Object newValue) sets the value of this field ❤ Examples:

public static void main(String[] args) throws Exception { //StudentBean(String id,String name,String ago) StudentBean Bean = new StudentBean("1"," king ","18"); Field fieldName = bean.getClass().getField("name"); // name is the variable name. String a = fieldname.get (fieldName); Set (fieldName," lee ") // Set the name value to "lee" // If you want to access a private Field Field fieldName = bean.getClass().getDeclaredFields("name"); fieldName.setAccessible(true); String a = fieldname.get (fieldName); King / / a =}Copy the code

Low Method [] getMethods (); Public Method ● Method[] getDeclaredMethods(); ● String getName(); ● Class[] getParameterTypes() — returns an array of parameter types ● Class getReturnTypes() — Return return value type ● int getModifiers(); Modifier- Returns an int value representing whether the method is public or privite String a=Modifier. ToString (class.getModiFIERS ()) a=class public

● Boolean isFinal(int MODIFIERS) ● Boolean isPublic(int Modifiers) ●isAbstract, isNative, isPrivate… , etc.

Low Constructors [] getConstructors (); Return the public constructor

Low Constructors [] getDeclaredConstructors (); Return all constructors

●String getPackageName() Returns the package name

●Class getType() gets the type

●Class getComponentType() gets the array component type

● Boolean isPrimitive() is a base type

Reflection application: publicclass TestController {
    public static void main(String[] args) throws ReflectiveOperationException {
        int[] test={1.5.7.8};
        System.out.println(new ObjectAnalyzer().toString(test));
        System.out.println("-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --");

        var test1=new ArrayList<>();
        test1.add(3); test1.add(8); test1.add(31); test1.add(1);
        System.out.println(new ObjectAnalyzer().toString(test1));
        System.out.println("-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --");

        DeviceVO deviceVO=new DeviceVO();
        deviceVO.setUserId("123456");
        List<DeviceBean> deviceBeans=new ArrayList<>();
        DeviceBean device=new DeviceBean();
        device.setId("1");
        device.setNickname("The king");
        device.setPassword("123");
        device.setDeviceId("H0100001");
        deviceBeans.add(device);
        deviceVO.setData(deviceBeans);
        System.out.println(new ObjectAnalyzer().toString(deviceBeans));

        System.out.println("-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --");
        System.out.println(newObjectAnalyzer().toString(device)); }} Print result: int{[1.5.7.8]}
---------------------------
java.util.ArrayList{[java.lang.Integer{value=3},java.lang.Integer{value=8},java.lang.Integer{value=31},java.lang.Integer{value=1}]}
---------------------------
java.util.ArrayList{[com.hsh.modules.app.vo.DeviceBean{id=1IP, uuid =, =, port =, nickname = king, username =, password =123,type=,devId=null,deviceId=H0100001,deviceName=null,deviceLocation=null,location=null,detailLocation=null,siteId=null,deviceid=null}]}
---------------------------
com.hsh.modules.app.vo.DeviceBean{id=1IP, uuid =, =, port =, nickname = king, username =, password =123,type=,devId=null,deviceId=H0100001,deviceName=null,deviceLocation=null,location=null,detailLocation=null,siteId=null,deviceid=null}
Copy the code
   / * * *@author
 * @date The 2021-03-30 17:23 *@desc  Reflection gets various types of values */
public class ObjectAnalyzer {
    private List<Object> visited=new ArrayList<>();// Tag array to see if the tag runs out
    // Print information about Objects
    public String toString(Object obj) throws ReflectiveOperationException{
        if (obj == null) return null;
        if (visited.contains(obj)) return "...";
        visited.add(obj);
        Class cl=obj.getClass();

        if (cl == String.class) return (String)obj; // The input parameter is String

        /** * is an array */
        if (cl.isArray()){
            String r=cl.getComponentType() + "{[" ; //getComponentType = getType()
            for (int i=0; i<Array.getLength(obj); i++){if (i > 0) r=r+",";
                Object val=Array.get(obj,i); // get item I from the list
                if(cl.getComponentType() == String.class){
                    r=r+val;
                }else if (cl.getComponentType().isPrimitive()){ // If not base type
                    r=r+val;
                } else{ r=r+toString(val); }}return r+"]}";
        }

        /** * the input argument is ArrayList */
        if (cl==ArrayList.class){
            String r=cl.getTypeName() + "{[" ; //getComponentType = getType()
            for (int i=0; i< ((ArrayList) obj).size(); i++){if (i > 0) r=r+",";
                Object val=((ArrayList)obj).get(i); // get item I from the list
                if(val.getClass() == String.class){
                    r=r+val;
                }else if (val.getClass().isPrimitive()){ // If the base type
                    r=r+val;
                } else{ r=r+toString(val); }}return r+"]}";
        }

        /** * is another type of object */
        String r=cl.getName();
        do {
            r=r+"{";
            Field[] fields=cl.getDeclaredFields(); // Get all the fields
            AccessibleObject.setAccessible(fields,true);// Set the access permission to private
            // Single set field.setaccessible (true);

            for (Field field:fields){// Fetch each field
                if(! Modifier.isStatic(field.getModifiers())){//Modifier translate Modifier
                    if(! r.endsWith("{")) r=r+","; // string.endswith () does not end with what
                    Object val=field.get(obj);
                    r=r+ field.getName() + "=";
                    if(field.getType() == String.class){
                        r=r+val;
                    }else if (field.getType().isPrimitive()){String is not a base type if it is not
                        r=r+val;
                    }else{ r=r+toString(field); }}}// if {start does not enter the for loop if is static
            if (r.endsWith("{")){
                r = r.substring(0,r.length() - 1);
            }else {
                r=r+"}";
            }
            cl=cl.getSuperclass();
        }while(cl! =null);

        returnr; }}Copy the code

Inherited design tips 1. Put common operations and fields in the parent class. Do not use protected fields. The mechanism does not provide more protection 1. Subclasses are infinite, and protected fields can be accessed from subclasses, breaking encapsulation. 2. In Java, protected fields are accessible as long as they are in a package, so there is no use for 3. Implement IS-A relation four. Do not use inheritance five unless all inheritance methods make sense. When overriding a method, do not change the original design idea: add in a parent class adds dates, and override add in a subclass adds people six. Use polymorphism, not type information example:

if(x instanceof ABean){ a(x); }else if (x instanceof BBean){ a1(x); } If x calls this method of this type, and if this other type calls another method, the methods of such a concept should be consolidated into one, put into a parent class or interface, and then execute using the dynamic allocation mechanism of polymorphism. X.a () is easier to maintain and extend using polymorphism and interfaces; (Parent or interface)Copy the code

Reflection allows us to look at method fields at run time and write more generic code, but it bypasses the compiler’s detection and makes the code more vulnerable.

5. The interface

Interface – Interface Implement – Implements inner class – inner class

An interface is not a class, but rather a set of requirements for classes that want to conform to that interface. The default interface is Public + abstract

1. The interface is not a class and therefore cannot be instantiated directly with new. x=new Comparable(); / / wrong

2. Interfaces can be declared and methods can be called. Comparable x; x.compareTo(); / / for (a lot of direct call service in Java ArcDataChangedEntity arcData = arcService. GetNewestDeviceDetail (deviceId);)

We can use instanceof to verify that this class implements an if(ABean instanceof Comparable)// pair

Public Interface AppVersionMessageService extends IService< AppVersionMessageEntity> {}

5. The fields in the interface can only be constants, and the variables in the interface have public static final by default. Public interface ApiService {String httpUrl = “www.hsh-iot.com/”; String httpUrl1 = “www.hsh-iot.com/111”; }

Interface rounding is equivalent to the abstract method of the superclass, and subclass inheritance is implemented. Why not? Because Java can extend only one parent class, Implement can implement multiple interfaces. This avoids the complexity and inefficiency of multiple inheritance. public abstract int compareTo(Obj o); // Subclass inheritance implements this method

7. Static and private methods are allowed in java8 interfaces. However, the common practice is to create a companion class of the interface and put the static private class in the companion class. E.g. Collection/ Collections or Path/Paths.

8. The default implementation can be modified with default

Clone objects

A a=new A(); A b=a; //b simply copies a reference to object A, both of which point to the same object. This is not a real clone.

If you want to clone an object, you need to implement the Cloneable interface (this interface is just a tag interface, there is no implementation method, you need to write clone ()).

    public static void main(String[] strings) {
        IOBean ioBean=new IOBean(9.10);
        IOBean ioBean1=null;
        try {
            ioBean1=ioBean.clone();
            ioBean1.setStart(100);
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        System.out.println(ioBean);  9 / / results
        System.out.println(ioBean1); 100, / / results
      }
        
      public static class IOBean implements Cloneable{  
          double start,end;
          public IOBean (double start,double end){
            this.start=start;
            this.end=end;
        }
        @Override
        protected IOBean clone() throws CloneNotSupportedException {
            return (IOBean) super.clone();
        }
Copy the code
Shallow copy

Clone (Object. Clone ()) is a shallow copy. That is, the object referenced in the copied object is not really copied, just copied.

Deep copy

On a shallow-copy basis, objects referenced by objects also implement the Cloneable interface and clone methods.

6. Lambda expressions

A lambda expression is a succinct syntactically defined block of code. So a lambda expression is just a block of code and a specification of the variables that must be passed in. Lambda expressions: arguments, arrows (->), and an expression. Empty ()->{}; (String a, String b) -> a.compareTo(b)

(a,b) -> a.compareTo(b)

It is not necessary to specify a lambda expression return value type. Because the return type is inferred from the context. The above returns an int.

  1. Functional interface

Sort (arr, (a, b) -> a.compareTo(b));

The ArrayList class has a method called removeIf that accepts lambda expressions. RemoveIf (b->b==null) // Remove all null from the list

  1. Method references

Sort (STR,String :: compareToIgnoreCase) // Sort STR case insensitive; aaa.stream().mapToDouble(Temporary :: getTimeLength).sum();

  1. Constructor reference

If you want to call the constructor, the method is called new aaa.stream().map(Temporary :: new).collect(Collectors. ToList ());

  1. Variable scope

Variables captured in lambda expressions must actually be final of fact

Accessing an external method or variable in a lambda expression does not change that variable (the actual final variable).

B is in, minus 1 is out.

Lambda expressions use this, which is the this argument to the method that creates the lambda expression

This is this of ro, not this of ActionListener

  1. Working with lambda expressions

The point of using lambda expressions is to defer processing. Lambda expression usage scenarios ● Code running in a single thread, in a thread ● Code running multiple times, in a loop ● In an algorithm (sorting) ● Listening (data arrives, button clicks)

Iobeans: sort by start, According to the end if the same sort Arrays. Sort (ioBeans, Comparator.com paringDouble (IOBean: : getStart). ThenComparingDouble (IOBean: : getEnd));

Sorting can be implemented directly with the lambda expression of Comparator.comparing

7. The inner class

An inner class can call data from its parent class, including private ones (the compiler automatically adds a reference to the parent class when calling data from the inner class that created it).

Local inner class

An inner class declared ina method cannot be accessed by anyone other than that method, or even have a Public or private local inner class. When a class calls a local variable ina method, it must be final, just as a lambda expression calls a variable outside the method

Anonymous inner class

When an inner class inherits a class or implements an interface, you can omit the name of the inner class and use new + the name of the interface. This is called an anonymous inner class

newImplement interface/superclass constructor (argument list) () {// The body part of the anonymous inner class
}
Copy the code



To use anonymous inner classes, we must either inherit a class or implement an interface, but not both. We can only inherit a class or implement an interface.

You cannot define constructors in anonymous inner classes.

An anonymous inner class cannot have any static member variables or methods.

Anonymous inner classes are local inner classes, so any restrictions that apply to local inner classes also apply to anonymous inner classes.

An anonymous inner class cannot be abstract. It must implement all the abstract methods of the inherited class or interface.

Anonymous inner class examples: Various interface callbacks, which are not implemented through Implement, are actually new to anonymous inner classes.

Anonymous inner classes can be implemented using lambda expressions (listening, callback, etc.)

Static inner class

If you want an inner class to be unable to access its parent (without generating references to its enclosing class), declare it as a static inner class. Classes cannot be declared as static. Static inner classes can use static methods and static variables, and other inner classes cannot be declared in interfaces

Agent 8.

A proxy can create a new class proxy pattern at run time that implements a given set of interfaces and provides a proxy object to an object that controls references to the original object. Generally speaking, the agency model is a common intermediary in our life. Objective :(1) to access the target object indirectly by introducing proxy object, so as to prevent unnecessary complexity brought to the system by direct access to the target object; (2) Access control through proxy objects;



The proxy mode has three roles:

Abstract role: Refers to the public methods provided by the proxy role and the real role, usually as an interface

Real roles: You need to implement an abstract role interface that defines the business logic that real roles implement for invocation by proxy roles. That’s where the real business logic is.

Proxy role: Needs to implement the abstract role interface, is a proxy for the real role, through the real role’s business logic methods to implement the abstract method, and can attach its own operations. Put unified process control into the agent role!

Static proxy Write dead proxy.

A dynamic proxy

Dynamic proxies are essentially the same as static proxies, most importantly the Proxy class is created with proxy.newProxyInstance ().

Abnormal 9.

Exception objects are inherited from the Throwable class.

Anomalies are classified as follows: ① Check anomaly ② non-check anomaly see the figure above

Checking exceptions: The compiler automatically checks if you have written an exception handler.

Like reading a random file

Abnormal statement

Declare exceptions: +throws+ exception name after the method name, as shown below

Throws FileNotFoundException or try{}catch() to declare an exception

If there are multiple check exceptions, list them all and separate them with commas (,). Throws FileNotFoundException, EOFException. However, non-checking exceptions do not need to be declared (Error or RuntimeException). They are either system exceptions or they were written incorrectly.

An exception is thrown

Throw an exception: throw+new+ The name of the exception, as shown below



If there is an appropriate exception, it will throw it directly. If there is no appropriate exception defined by the system, it will customize the exception.

Custom exception You can define a custom exception if the system exception does not meet requirements. Inheriting from Exception or a subclass of Exception.

This is the class with the failed login shown above.

Catching an exception If an exception occurs but is not caught anywhere, the program terminates.

The stack trace

When a Java program terminates due to a tweet or exception, the stack trace, also known as the error log, is displayed

You can use the throwable. PrintStackTrace (new PrintWriter (stringWriter)) to access the text description of the stack trace information.

Low Throwable (Throwable cause) -vice Throwable (String MSG, Throwable cause) Exception low/RuntimeException construct a Throwable object Throwable initCause(Throwable cause) Set Cause Cause ● Throwable getCause() Cause the Throwable is abnormal ● getStackTraceElement GetStackTrace () gets the stack trace

1. Exceptions are not a substitute for simple tests such as

 if(! S.e mpty ()) s.r UN (); withtry{
  s.run();
  }catch(EmptyStackException e){} Run () does not run if it is emptyCopy the code

2. Don’t overelaborate exceptions. Don’t try one line of code, try one line of code

3. Take advantage of the exception hierarchy to throw specific exceptions, not just the big class: RuntimeException

4. Don’t suppress exceptions. Handle exceptions as they come in, or throw them out

5. Throw early, catch late

10. Assertion – assert

The assertion mechanism allows some checks to be inserted into the code during testing that are automatically removed from the formal code.

Assert x>=0 assert x>=0 and return x assert x>=0:x

Enable and disable assertions are disabled by default. These are all functions in the classloader. Enable: -ea java-ea :MyClass -EA :com.my.liy Myapp Disable: -da java-da :MyClass -da:com.my.liy Myapp

11. The log

Advantages: ● Easy to turn on or off logging at a certain level (all) ● Minimal logging code overhead ● Log records can be formatted in different ways ● Loggers can be filtered by processors ● Multiple loggers can be enabled ● Configuration of the logging system is controlled by configuration files

Basic log Global loggers generate log logger.getGlobal ().info(” AAA “); Cancel all logs logger.getGlobal ().setlevel (level.off);

Global

Private static final Logger myLogger = logger.getLogger (” com.my.myapp “); Static: If not declared static, it may be garbage collected if not called

Loggers also have a hierarchy, and subclasses inherit and use the logging level of their parent class. SERVERE- Severe WARNING- WARNING INFO- INFO CONFIG- FINE FINER FINEST You can also set which Level to display setLevel (), or turn level. ALL on or level.off OFF

Print a log, logger.log (level, contents)

Logger.getLogger(“com.test.proxy.dynamic_proxy”).log(Level.SEVERE,”99999999999999999″);

Generic programming

My own article generic supplement: juejin.cn/post/695096…

Before generics, this was done by inheriting objects (such as Object[] maintained in ArrayList). This code was cumbersome and had two problems. This is exactly what generics are good for: they make programs readable and more secure

  1. When fetching a value, it must be strongly rotated

Before generics, ArrayList only maintained a reference to Object[]

  List list=newList(); List is not generic, just oneObject[], and a List <StringThis is genericsString a=(String)list.get(0);
Copy the code
  1. No error checking, any type can be added, so it’s easy to get an error when it’s strong, okay
  List list=new List();  
  list.add(0);
  list.add("111");
Copy the code

Generic method

Generic methods can be defined in ordinary or generic classes. Generics can only be used on objects. If the list. The add (1); The compiler will automatically convert int-> to Integer, a process called autoboxing, and get is called autounboxing

Generics in virtual machines

There are no generic type objects in the virtual machine – all objects are ordinary classes.

Type erasure

Whenever a generic type is defined, a corresponding primitive type is automatically provided. The name of the primitive type is the generic type name with the type removed (List

a; a.getClass().getName(); = Java. Util. ArrayList). The type variable is erased, Pair

all T’s are replaced with Object Pair

All T’s are replaced with Comparable (if there are more than one T’s, it becomes the first one)


After the erasing is done, to fetch the return type, the compiler will automatically insert strong code to force us to the correct type

After erasing, replace type T with one of these types, but there may be more than one method (polymorphic), such as Object.tostring, string.toString. To preserve polymorphism, the compiler generates a bridge method

● There are no generics in the virtual machine, only ordinary classes and methods ● All type parameters are replaced with their qualified types ● Bridge methods are synthesized to remain polymorphic ● Strong transitions are inserted when necessary to preserve type safety

Limitations: Generic arrays are not supported

Wildcard: Allows type parameters to change

Wireless fixed wildcard: a direct one? Pair
Pair

public static Boolean hasNulls(Pair
        p){
 return p.getFirst()==null;
}
Copy the code

Type literals generic erase problem :List,List primitive type is List, how to tell, let it have a different action? Construct an anonymous inner class (same as Gson, new Gson().fromjson (s, new TypeToken

() {}.gettype ());)

{} indicates that this creates an anonymous inner class, without {} it is an object. If it is an Object, then the generic T is erased and becomes Object. But a + {} instead declares an anonymous inner class. T becomes a class, erasing a class file, and T points to that file. (Approximate name)XXX. The BaseBean $1. Class.this$1.classIs an anonymous inner class of BaseBean. Then there is no T generic inside the anonymous inner class, which is a concrete ParameteBean that will not be erased