JavaSE Notes and Reflections for Java Learning Notes

1. Notes

1.1 What are notes

  • Annotation is a new technology introduced from JDK5.0
  • The role of Annotation:
    • It is not the program itself, it can be interpreted. (This is no different from comment.
    • Can be read by other programs (e.g., compilers, etc.)
  • Format of Annotation:
    • Comments exist in the code as'@comment name', and you can add parameter values such as: @SuppressWarnings(value='unchecked').
  • Where is Annotation used?
    • They can be attached to package s, class es, method s, field s, and so on, which is equivalent to adding additional auxiliary information to them, and we can access these metadata programmatically through the reflection mechanism
package com.Annotation;

public class Test01 {
    // Annotation for @Override (method) override
    @Override
    public String toString() {
        return super.toString();
    }
}

1.2 Built-in Notes

  • @Override: Defined in java.lang.Override, this comment applies only to rhetorical methods, indicating that a method declaration intends to override the declaration of another method in a superclass
  • @Deprecated: Defined in java.lang.Deprecated, this comment can be used for rhetoric methods, attributes, classes, to indicate that programmers are not encouraged to use such elements, usually because they are dangerous or have better options
  • @SuppressWarnings: Defined in java.lang.SuppressWarnings to suppress compile-time warnings.
    • Unlike the first two notes, you need to add a parameter to use it correctly. These parameters are all defined, so let's use them selectively
    • @SuppressWarnings("all")
    • @SuppressWarnings("unchecked")
    • @SuppressWarning(value={"unchecked","deprecation"})
    • etc...
package com.Annotation;

import java.util.ArrayList;
import java.util.List;

public class Test01 {
    // Annotation for @Override (method) override
    @Override
    public String toString() {
        return super.toString();
    }

    @Deprecated
    public static void test() {
        System.out.println("Deprecated");
    }

    @SuppressWarnings("all")
    public static void test1() {
        List list = new ArrayList();
    }

    public static void main(String[] args) {
        test();
        test1();
    }
}

1.3 Yuan Annotation

  • Meta-annotations are responsible for annotating other annotations. Java defines four standard meta-annotation types that are used to provide descriptions of other annotation types
  • These types and the classes they support can be found in the java.lang.annotation package. (@Target, @Retention, @Document, @Inherited)
    • @Target: Used to describe the scope of use of a note (i.e., where the described note can be used)
    • @Retention: Indicates at what level the annotation information needs to be saved to describe the life cycle of the annotation
      • (SOURCE < CLASS < RUNTIME)
    • @Document: Indicates that the comment will be included in javadoc
    • @Inherited: Indicates that a subclass can inherit this comment from its parent
package com.Annotation;

//Test Meta Comment

import java.lang.annotation.*;

@MyAnnotation
public class Test002 {
    @MyAnnotation
    public void test() {

    }
}

//Define a comment
//Target indicates where our notes can be used
@Target(value = {ElementType.METHOD, ElementType.TYPE})

//Retention indicates where our notes are still valid
@Retention(value = RetentionPolicy.RUNTIME)

//Documented indicates whether our annotations will be generated in Javadoc
@Documented

//Inherited subclasses can inherit annotations from the parent class
@Inherited
@interface MyAnnotation {

}

1.4 Custom Notes

  • When using @interface to customize annotations, the java.lang.annotation.Annotation interface is automatically inherited
  • Analysis:
    • _Interface is used to declare a comment in the format public @interface comment name {Define Content}
    • Each of these methods actually declares a configuration parameter
    • The name of the method is the name of the parameter
    • The return value type is the type of the parameter (return values can only be basic types, Class, String, enum)
    • Default values of parameters can be declared by default
    • If there is only one parameter member, the general parameter name is value
    • Annotation elements must have values. When we define annotation elements, we often use an empty string with 0 as the default value
package com.Annotation;

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

public class Test03 {
    //Annotations can be explicitly assigned, and if there is no default value, we must assign a value to the annotation
    //Parameters do not need to be sequential
    @MyAnnotation2(age = 18, name = "SolitudeAlma")
    public void test() {}
    @MyAnnotation3("SolitudeAma")
    public void test1() {}
}

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation2 {
    //Noted parameters: parameter type + parameter name ()
    String name() default "";
    int age();
    int id() default -1;//If the default value is -1, it does not exist

    String[] schools() default {"Tsinghua University", "Dali Dali University"};
}

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation3 {
    //If only one parameter is suggested to be named value, you can fill in the parameter without writing value
    String value();
}

2. Reflection

2.1 Introduction

  • Dynamic Language
    • A language that can change its structure at run time: for example, new functions, objects, or even code can be introduced, existing functions can be deleted, or other structural changes.Common sense is that code can change its structure based on certain conditions at runtime
    • Main dynamic languages: Object-C, C#, JavaScript, PHP, Python, etc.
  • Static Language
    • Corresponding to dynamic languages, static languages are those that have an inflexible runtime structure.Such as Java, C, C++.
    • Java is not a dynamic language, but Java can be called a "quasi-dynamic language".That is, Java is a bit dynamic, and we can use the reflection mechanism to get something like a dynamic language.Java Dynamics Makes Programming More Flexible

2.2 What is reflection

  • Reflection is the key to Java being considered a dynamic language. Reflection mechanisms allow programs to obtain internal information of any class during execution with the Reflection API and directly manipulate the internal properties and methods of any object.

Class c = class.forName("java.lang.String")

  • Once the class is loaded, a Class-type object (a class has only one Class object) is generated in the method area of heap memory, which contains the complete class structure information.From this object we can see the structure of the class.This object is like a mirror through which we can see the structure of a class, so our image is called reflection

package com.Reflection;

public class Test01 {
    public static void main(String[] args) throws ClassNotFoundException {
        //Obtaining class objects of classes by reflection
        Class<?> c = Class.forName("com.Reflection.User");
        System.out.println(c);

        Class<?> c1 = Class.forName("com.Reflection.User");
        Class<?> c2 = Class.forName("com.Reflection.User");
        Class<?> c3 = Class.forName("com.Reflection.User");

        //A class has only one class object in memory
        //When a class is loaded, the entire structure of the class is encapsulated in the class object
        System.out.println(c1.hashCode());
        System.out.println(c2.hashCode());
        System.out.println(c3.hashCode());
    }
}
//Entity class: pojo entity
class User {
    private String name;
    private int id;
    private int age;

    public User() {
    }

    public String getName() {
        return name;
    }

    public int getId() {
        return id;
    }

    public int getAge() {
        return age;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setId(int id) {
        this.id = id;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

2.3 Class Class

  • The following method is defined in the Object class and will be inherited by all subclasses
    • public final native Class<?> getClass();
  • The return value type of the above method is a Class class, which is the source of Java reflection. In fact, the so-called reflection is also well understood from the results of the program, that is, the name of the class can be derived from object reflection.
  • The information you get when an object looks in the mirror: the properties, methods, and constructors of a class, and what interfaces a class actually implements.For each class, the JRE maintains an object of the same Class type.A Class object contains information about a specific structure (class/interface/enum/annotation/primitive type/void/[])
    • Class itself is a class
    • Class objects can only be created by the system
    • A loaded class will only have one Class instance in the JVM
    • A class object corresponds to a.class file loaded into the JVM
    • Instances of each class will remember which Class instance they were generated from
    • Class gives you a complete picture of all the loaded structures in a class
    • Class classes are the root of Reflection s. For any class that you want to dynamically load and run, you must first get the corresponding Class object
Method NameFunctional description
sta
tic ClassforName(String name)
Returns a lass object with the specified Class name
Object newInstance()Call the default constructor to return an instance of the Class object
getName()Returns the name of the entity (class, interface, array class, or void) represented by this Class object
Class getSuperClass()Returns the Class object of the parent class of the current Class object
Class[] getInterfaces()Gets the interface of the current Class object
ClassLoader getClassLoader()Returns the class loader for this class
Constructor[] getConstructors()Returns an array containing some Constructor objects
Method getMethod(String name, Class... T)Returns a Method object with a parameter type of param Type
Field[] getDeclaredFields()Returns an array of Field objects
  • Get an instance of the Class class
    • If a specific class is known, it is obtained by the class attribute of the class, which is the most secure and reliable method with the highest program performance.

Class clazz = Person.class;

  • Given an instance of a class, call its getClass() method to get the Class object

Class clazz = Person.getClass();

  • The full class name of a class is known and, under the class path, can be obtained by the static method forName() of the Class class, possibly throwing a ClassNotFoundException exception

Class clazz = Class.forName("demo01.Srudent");

  • Built-in basic data types can have direct class names.Type
  • ClassLoader can also be used
package com.Reflection;

//Test Class Creation
public class Test02 {
    public static void main(String[] args) throws ClassNotFoundException {
        Person person = new Student();
        System.out.println("This person is:" + person.name);

        //Mode 1: Obtain by Object
        Class<? extends Person> class1 = person.getClass();
        System.out.println(class1.hashCode());
        //Mode 2: forName acquisition
        Class<?> class2 = Class.forName("com.Reflection.Student");
        System.out.println(class2.hashCode());
        //Mode 3: Obtained by class name.class
        Class<?> class3 = Student.class;
        System.out.println(class3.hashCode());
        //Mode 4: Packaging classes of basic built-in types all have a Type attribute
        Class<Integer> class4 = Integer.TYPE;
        System.out.println(class4);

        //Get parent type
        Class<?> class5 = class1.getSuperclass();
        System.out.println(class5);
    }
}

class Person {
    public String name;

    public Person() {
    }

    public Person(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                '}';
    }
}

class Student extends Person {
    public Student() {
        this.name = "Student";
    }
}

class Teacher extends Person {
    public Teacher() {
        this.name = "Teacher";
    }
}

2.4 All types of Class objects

  • Those classes can have Class objects
    • Class: external class, member (member internal class, static internal class), local internal class, anonymous internal class
    • Interface: interface
    • []: Array
    • enum: enumeration
    • annotation: comment@interface
    • primitive type: basic data type
    • void
package com.Reflection;

import java.lang.annotation.ElementType;

//All types of class es
public class Test03 {
    public static void main(String[] args) {
        Class<?> class1 = Object.class;    //class
        Class<?> class2 = Comparable.class;    //Interface
        Class<?> class3 = String[].class;  //One-dimensional array
        Class<?> class4 = int[][].class;   //2-D Array
        Class<?> class5 = Override.class;  //annotation
        Class<?> class6 = ElementType.class;   //enumeration
        Class<?> class7 = Integer.class;   //Basic data types
        Class<?> class8 = void.class;  //void
        Class<?> class9 = Class.class; //Class

        System.out.println(class1);
        System.out.println(class2);
        System.out.println(class3);
        System.out.println(class4);
        System.out.println(class5);
        System.out.println(class6);
        System.out.println(class7);
        System.out.println(class8);
        System.out.println(class9);

        //As long as the element type is consistent with the dimension, it is the same CLass
        int[] a = new int[10];
        int[] b = new int[100];
        System.out.println(a.getClass().hashCode());
        System.out.println(b.getClass().hashCode());
    }
}

Subsidiary Code
All resources come from the Video of Crazy Talk on Station B

Tags: Java

Posted on Fri, 03 Sep 2021 12:27:48 -0400 by blawson7