Summary of java reflection knowledge points

Keywords: Java Back-end

1. Three ways to obtain class objects

hello h = new hello();
//1. Obtain class objects through instance objects
	Class class1 = h.getClass();
	System.out.println(class1);
	System.out.println(class1.hashCode());
//2. Get class object by object name
	Class class2 = hello.class;
	System.out.println(class2);
	System.out.println(class2.hashCode());
//3. Get Class object through Class static method
	Class<?> class3 = Class.forName("hello");
	System.out.println(class3);
	System.out.println(class3.hashCode());

//Operation results:
class hello
1163157884
class hello
1163157884
class hello
1163157884

The process has ended,Exit code 0

//The hash values of the three are the same, indicating that an object has only one class object.

2. Common operations

2.1 get all construction methods

public class hello {
    private String name;

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

    public hello() {
    }

    public static void main(String[] args) throws Exception {
        hello h = new hello();
        //1. Obtain class objects through instance objects
        Class class1 = h.getClass();
        //2. Get construction method
        Constructor[] constructors = class1.getConstructors();
        //3. Traverse the array and print it
        for (Constructor con:
             constructors) {
            System.out.println(con);
        }
    }
//Operation result: there are 2 construction methods in total, and 2 of them are printed out
public hello(java.lang.String)
public hello()
}

2.2 get only parameterless constructs and create objects

Class<?> class3 = Class.forName("hello");
        Constructor<?> c = class3.getConstructor();//Get parameterless constructor
        Object o = c.newInstance();//Creating objects with parameterless construction
        System.out.println(o);
 Print results:
 I was executed (because I printed this sentence in the nonparametric structure, so I explained the object o (executed)
hello@74a14482       

Easy to create objects with parameterless methods:
(Directly create with class object)
Object o = class3.newInstance();
        System.out.println(o);

2.3 get the structure with parameters and create objects

Class<?> class3 = Class.forName("hello");
        Constructor<?> c = class3.getConstructor(String.class);//Get the parameter structure, write the data type with parameter structure in parentheses, and then add. class
        Object o = c.newInstance("Handsome pot");//To create an object, you must fill in parameters, or an error will be reported
        System.out.println(o);
//Print results:
Shuai pot (rewritten here) toString Method)

2.4 getmethods method

Public methods and inherited methods can be obtained, but private methods cannot be obtained

  hello h = new hello();
        Class class1 = h.getClass();
        Method[] m = class1.getMethods();
        for (Method me:m
                     ) {
            System.out.println(me.toString());
        }

2.5 getdeclaredmethods method

You can get all the methods in the class, including private methods. You can't get inherited methods

hello h = new hello();
        Class class1 = h.getClass();
        Method[] d = class1.getDeclaredMethods();
        for (Method m:d
             ) {
            System.out.println(m);
        }

2.6 get a single method and use it (no reference)

 hello h = new hello();
        Class class1 = h.getClass();
        Method m = class1.getMethod("ai");
        Object o = class1.newInstance();//create object
        m.invoke(o);//When called with this method, the first parameter is filled in the object, and the second parameter is args

2.7 get a single method and use it (with reference)

 hello h = new hello();
        Class class1 = h.getClass();
        Method m = class1.getMethod("ai",String.class);
        Object o = class1.newInstance();//create object
        m.invoke(o,"hello");//When called with this method, the first parameter is filled in the object, and the second parameter is args

2.8 private method acquisition and use

When other classes access this class, private methods cannot be accessed directly, so you need to kill permissions

student s = new student();
        Class class1 = s.getClass();
        Object o = class1.newInstance();
        Method ai = class1.getDeclaredMethod("ai");
        ai.invoke(o);
report errors:
Exception in thread "main" java.lang.IllegalAccessException: Class hello can not access a member of class student with modifiers "private"
	at sun.reflect.Reflection.ensureMemberAccess(Reflection.java:102)

The modification code is as follows:
student s = new student();
        Class class1 = s.getClass();
        Object o = class1.newInstance();
        Method ai = class1.getDeclaredMethod("ai");
        ai.setAccessible(true); //Change to true
        ai.invoke(o);

2.9 universal method of writing with reflection

 public static void main(String[] args) throws Exception {
        Properties p = new Properties();
        invokeAny(p,"setProperty",new Class[] {String.class,String.class},"Zhang San","24");
        System.out.println(p);
//Output result: {Zhang San = 24}

    }
    //The first parameter is the object
    //The second parameter is the name of the method to call
    //The third parameter is the format of the parameter
    //The fourth parameter is the specific value of the parameter
    public static Object invokeAny(Object obj,String methodName,Class<?>[] types,Object ...args) throws Exception {
        Class<?> class1 = obj.getClass();
        Method method = class1.getMethod(methodName, types);
        return method.invoke(obj,args);
    }

2.10 getFields method

Public attributes can be obtained, and inherited attributes must also be public. Private attributes cannot be obtained

 Class class1 = Class.forName("hello");
        Field[] fields = class1.getFields();

2.11 getdeclaraedfields method

You can get all properties, except inherited properties

Class class1 = Class.forName("hello");
        Field[] fields = class1.getDeclaredFields();
        for (Field f :
                fields) {
            System.out.println(f.toString());
        }

2.12 get a single attribute and use

Class class1 = Class.forName("hello");
        Field age = class1.getDeclaredField("age");
        Object o = class1.newInstance();//create object
        age.set(o,12);//assignment
        System.out.println(age.get(o));//Get value

2.13 private attribute acquisition

 public static void main(String[] args) throws Exception {
        Class<?> class1 = Class.forName("student");
        Field age = class1.getDeclaredField("age");
        Object o = class1.newInstance();
        age.set(o,14);
        System.out.println(age.get(o));
//An error is reported. The private attribute must kill the permission


    }
    
Correct writing:

    public static void main(String[] args) throws Exception {
        Class<?> class1 = Class.forName("student");
        Field age = class1.getDeclaredField("age");
        Object o = class1.newInstance();
        age.setAccessible(true);//Get access
        age.set(o,14);

        System.out.println(age.get(o));


    }

3. Factory design mode

What is a design pattern? In short, it is a routine, a template, a set of design patterns to deal with some known errors, just like the sales routine;
Factory pattern is mainly responsible for object creation
It is divided into four roles: 1. Parent product; 2. Child product; 3. Factory; 4. Customer program
Xiaokeng record 1: if you are writing a text file, remember not to add a semicolon manually; it is not necessary to add it. If you add it, it is equivalent to a semicolon, which will be loaded in, resulting in an error.

1. Define an interface

public interface Usb {
   void service();
}

2. Subclass products to implement this interface

Mouse:
public class Mouse implements Usb{
    public void service() {
        System.out.println("The mouse is connected");
    }
}
U Disk:
public class Upan implements Usb{
    public void service() {
        System.out.println("U The disk starts working");
    }
}

3. Establish factory

public class Factory {
    public static Usb createUsb(String property) throws Exception {
        Usb usb = null;//Creating objects with interfaces
        Class<?> class1 = Class.forName(property);
        //Get class object by reflection
        usb=(Usb)class1.newInstance();
        //New object
        return usb;//Return this object
    }
}

4. Customer procedures

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Properties;
import java.util.Scanner;

public class Demo {
    public static void main(String[] args) throws Exception {
        System.out.println("1 Fan, 2 mouse");
        Scanner s = new Scanner(System.in);
        String choice = s.next();
        Properties properties = new Properties();
        //Create a collection
        FileInputStream fileInputStream = new FileInputStream("src\\main\\java\\world");
        properties.load(fileInputStream);
        //Record the data in IO through the characteristics of this set
        fileInputStream.close();
       Usb usb=Factory.createUsb(properties.getProperty(choice));
       //Call the method in the factory and find the corresponding class name through the entered sequence number
       //Then judge
       if (usb!=null){
           System.out.println("Purchase successful");
           usb.service();
       }
       else {
           System.out.println("Purchase failed, product does not exist");
       }
    }
}

5. Save all the class names in a file, and then add subclass products. You only need to add a class name, and there is no need to write logic code again

1=Mouse
2=Upan

4. Singleton mode

4.1 hungry wolf singleton mode

Advantages: thread safety;
Disadvantages: it will also be created when it is not applicable, wasting memory space

public class hello {
    public static final hello a=new hello();
    private hello(){};
    public static hello getHello(){
        return a;
    }
}

Test code

public static void main(String[] args) {
    hello h = hello.getHello();
    System.out.println(h.hashCode());
    hello h1 = hello.getHello();
    System.out.println(h1.hashCode());
}

Output results

1956725890
1956725890

4.2 lazy singleton mode

Advantages: it will not be instantiated when it is not applicable and will not waste memory space;
Disadvantages: thread unsafe

public class hello {
    public static hello a =null;
    private hello(){};
    public static hello getHello(){
        if (a==null){
            a=new hello();
        }
        return a;
    }
}

Test code
   public static void main(String[] args) {
        for (int i = 0; i < 3; i++) {
            new Thread(new Runnable() {
                public void run() {
                    System.out.println(hello.getHello().hashCode());
                }
            }).start();
        }
    }
Print results:
1765939285
493184190
493184190

Add synchronization method or synchronization code block
  public static synchronized hello getHello(){
        if (a==null){
            a=new hello();
        }
        return a;
    }

4.3 static inner class singleton mode

It is also lazy in nature, which saves space and thread safety

public class hello {
    private hello(){};
    private static class b{
    //Hidden classes, which cannot be accessed outside, can only be accessed through getHello
    //Therefore, it will not be created by itself and will not waste memory space
        static hello a =new hello();
    }
    public static hello getHello(){
        return b.a;
    }

}

5. Enumeration type

public enum World {
//The enumeration keyword is enum and the class keyword is class;
        name,age;
        //This is an enumeration constant, which must be present and placed at the front of all codes
        String en;
        //You can define attributes
        private World(){};
        //You can define a private constructor. If it is public, an error will be reported
        public void hel(){
        }
        //Other methods can be defined;
}

5.1 enumeration combined with switch

 public static void main(String[] args) {
        World name = World.name;
        switch (name){
            case name:
                System.out.println("name");
                break;
            case age:
                System.out.println("Age");
                break;
        }
    }

The enumeration code is as follows:
public enum World {
        name,age;

}

6 notes

6.1 creating annotations

public @interface MyAnnotation {
//Properties (similar methods)
    String student();
    //Parentheses should be added, otherwise an error will be reported
    int cardId();
    //You can add default to set the default value
    int num() default 13;
}

6.2 special usage value

public @interface MyAnnotation {
    String value();
    //When there is only one attribute and the attribute name is value
}
public class hello {
	//You can omit value = "little apple" when passing parameters,
	//Can write directly;
    @MyAnnotation("Little apple")
    public static void main(String[] args) {

    }
 Note: only yes value And only when there is one attribute
 Multiple attributes must be written as before   
}

6.3 yuan notes

An annotation used to describe an annotation

There are three types:
1.RetentionPolicy.CLASS((default) annotations are recorded in the Class In the file, when running the program, JVM No retention
2.RetentionPolicy.RUNTIME: Run time JVM The annotation is retained and can be obtained through reflection
3.RetentionPolicy.SOURCE:Discard annotations directly at compile time

6.4 obtaining annotations by reflection

1.Define an annotation and use meta annotations
@Retention(value = RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
    String value() ;
}
2.Using annotations
@MyAnnotation("Little apple")
    public static void hi(){
        System.out.println("hello");
    }
3.Get annotation information through reflection
public class student{
    public static void main(String[] args) throws Exception {

        Class<?> hello = Class.forName("hello");
        Method main = hello.getMethod("hi");
        MyAnnotation annotation = main.getAnnotation(MyAnnotation.class);
        System.out.println(annotation.value());
    }
}
Print result: Little Apple

6.5 yuan annotation Target

Specifies that annotations can be used to decorate classes or methods

@Target(value = {ElementType.TYPE})
//Representation can only be used for classes, not methods
public @interface MyAnnotation {
    String value() ;
}

@Target(value = {ElementType.METHOD})
//The representation can only be used for methods, not classes
public @interface MyAnnotation {
    String value() ;
}

Posted by castor_troy on Sat, 27 Nov 2021 14:03:43 -0800