Java learning notes

annotation

Built in Annotation

  • @Override indicates that a method declaration intends to override another method declaration in the superclass
  • @Deprecated means that programmers are discouraged from using such elements, usually because it is dangerous or there are better choices
  • @SuppressWarnings is used to suppress compile time warnings
    • Parameter all unchecked depreciation

Meta annotation

  • Notes explaining other notes
    • @Target: describes the scope of use of annotations
    • @Retention: describes the lifecycle of the annotation (where it is valid) (runtime > class > source)
    • @Documented: indicates that the annotation will be included in the javadoc
    • @Inherited: indicates that the subclass can inherit the annotation in the parent class
//Custom annotation
@Target(value = {ElementType.METHOD,ElementType.TYPE})//Yes, only one parameter can omit value=
//@Target({ElementType.METHOD,ElementType.TYPE})
@Retention(value = RetentionPolicy.RUNTIME)
@Documented
@Inherited
@interface MyAnnotation{
    //Annotated parameters: parameter type + parameter name + ();
    String value() default "";//Default default value if there is no default value, the parameter must be passed. If there is only one parameter, the return value type can only be the basic type
}

reflex

Java Reflection

  • Reflection mechanism allows the program to obtain the internal information of any class with the help of Reflection API during execution, and can directly operate the internal properties and methods of any object
  • After loading the Class, a Class object is generated in the method area of heap memory (a Class has only one Class object), which contains the complete Class structure information

Common methods of Class

Method nameFunction description
static ClassforName(String name)Returns the Class object with the specified Class name
Object newInstance()Call the default (parameterless) 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 whose formal parameter type is param Type
Field[] getDeclaredFields()Returns an array of Field objects

Get an instance of Class

  1. If a specific class is known, it is obtained through the class attribute of the class. This method is the most safe and reliable, and the program performance is the highest:

    Class clazz = Person.class;
    
  2. If an instance of a Class is known, call the getClass() method of the instance to obtain the Class object:

    Class clazz = person.getClass();
    
  3. If the full Class name of a Class is known and the Class is under the Class path, it can be obtained through the static method forName() of Class class. ClassNotFoundException may be thrown

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

Get class information

package base;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class Demo06 {

    public static void main(String[] args) throws Exception {
        Class c1 = Class.forName("base.User");
        User user = new User();

        //Get the name of the class
        System.out.println(c1.getName());//Get package name + class name
        System.out.println(c1.getSimpleName());//Get class name

        //Get the properties of the class
        Field[] fields = c1.getFields();//Only public properties can be found
        for (Field field : fields) {
            System.out.println(field);
        }
        fields = c1.getDeclaredFields();//Find all properties
        for (Field field : fields) {
            System.out.println(field);
        }

        //Gets the value of the specified property
        Field name = c1.getDeclaredField("name");
        System.out.println(name);

        //Method to get class
        Method[] methods = c1.getMethods();//Get all public methods of this class and its parent class
        for (Method method : methods) {
            System.out.println("getMethods: " + method);
        }
        methods = c1.getDeclaredMethods();//Get all methods of this class (including private)
        for (Method method : methods) {
            System.out.println("getDeclaredMethods: " + method);
        }

        //Gets the specified method
        Method getName = c1.getMethod("getName");
        System.out.println(getName);
        Method setName = c1.getMethod("setName", String.class);//Method has parameters that need to be passed in
        System.out.println(setName);

        //Gets the specified constructor
        Constructor[] constructors = c1.getConstructors();//Get the public constructor of this class
        for (Constructor constructor : constructors) {
            System.out.println(constructor);
        }
        constructors = c1.getDeclaredConstructors();//Obtain all construction methods of this class
        for (Constructor constructor : constructors) {
            System.out.println(constructor);
        }

        //Gets the specified constructor
        Constructor declaredConstructor = c1.getDeclaredConstructor(String.class, int.class);
        System.out.println("Specified constructor: " + declaredConstructor);
        
    }
}

class User {
    private String name;
    private int age;

    public User() {
    }

    public User(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

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

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

Dynamically create object execution methods

package base;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class Demo07 {
    public static void main(String[] args) throws Exception {
        //Get Class object
        Class c1 = Class.forName("base.User");

        //Construct an object
        User user = (User) c1.newInstance();//Call parameterless constructor
        System.out.println(user);

        //Creating objects with a parameterized constructor
        Constructor declaredConstructor = c1.getDeclaredConstructor(String.class, int.class);
        User zs = (User) declaredConstructor.newInstance("zs", 18);
        System.out.println(zs);

        //Calling methods through reflection
        User user2 = (User) c1.newInstance();
        //Acquisition method by reflection
        Method setName = c1.getDeclaredMethod("setName", String.class);
        //invoke activation parameter (object, "value of method") object: the object that needs to execute the method
        setName.invoke(user2, "zs");
        System.out.println(user2.getName());

        //Operation properties by reflection
        User user3 = (User) c1.newInstance();
        Field name = c1.getDeclaredField("name");
        //Private properties cannot be operated directly. We need to turn off the security detection of the program. The property or method. setAccessible(true);
        name.setAccessible(true);
        name.set(user3, "zs");
        System.out.println(user3.getName());s
    }
}

Get generic information by reflection

Reflection operation annotation

ORM

  • Object relationship mapping -- > object relationship mapping
    • Correspondence between class and table structure
    • Attribute and field correspondence
    • Object and record correspondence
  • Annotation and reflection can be used to complete the mapping relationship between class and table structure

Keywords: Java

Added by o3d on Fri, 03 Sep 2021 02:15:46 +0300