Location>code7788 >text

java fundamentals - reflection notes

Popularity:768 ℃/2024-09-24 01:32:48

710, Reflection Quick Start

 

Code:

 

First create a file:

classfullpath=
method=hi

package ;

public class Cat {
    private String name = "Fortune Cat";
    public void hi() { //Common methods
        ("hi " + name);
    }
}
package ;

import ;

import ;
import ;
import ;
import ;
import ;
import ;
import ;

//Introduction of the reflection problem
public class ReflectionQuestion {
    public static void main(String[] args) throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        //Based on the information specified in the configuration file, create a Cat object and call the method hi

//The traditional way new object - " call method
//        Cat cat = new Cat();
//        ();

        //Let's try to do it -> understand reflexes
//1. Using the Properties class, you can read and write configuration files.
        Properties properties = new Properties();
        (new FileInputStream("src\\"));
        String classfullpath = ("classfullpath").toString();//""
        String methodName = ("method").toString();
        ("classfullpath=" + classfullpath);
        ("method=" + methodName);

        //2. Creating objects, the traditional way, doesn't work => Reflection mechanism
//        Cat cat1 = new ();
//        new classfullpath();//This is a String, not a class name.

//3. Use of reflection mechanisms
//(1) Load class, return object cls of type Class
        Class cls = (classfullpath);

        //(2) Get the object instance of the class you loaded via cls.
        Object o = ();
        ("Run type of o = " + ());//Type of operation

//(3) Get the methodName "hi" of the class you loaded via cls.
// I.e., in reflection, methods can be treated as objects (everything is an object).
        Method method1 = (methodName);
        ("===================");
//(4) pass (a bill or inspection etc)method1 invoke a method: I.e., calling a method is implemented through a method object (o);
//Traditional methods Object. Method() , Reflection mechanism Method.invoke(object) } }

Run results:

 

713, Reflection Related Classes

 

Code:

 

The code remains unchanged.

package ;

public class Cat {
    private String name = "Fortune Cat";
    public int age = 10;

    public Cat() {} //unparameterized constructor

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

    public void hi() { //Common methods
        ("hi " + name);
    }
}

 

package ;

import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;

public class Reflection01 {
    public static void main(String[] args) throws Exception {
        //1. Using the Properties class, you can read and write configuration files.
        Properties properties = new Properties();
        (new FileInputStream("src\\"));
        String classfullpath = ("classfullpath").toString();//""
        String methodName = ("method").toString();
        //3. Use of reflection mechanisms
//(1) Load class, return object cls of type Class
        Class cls = (classfullpath);

        //(2) Get the object instance of the class you loaded via cls.
        Object o = ();
        ("Run type of o = " + ());//Type of operation

//(3) Get the methodName "hi" of the class you loaded via cls.
// I.e., in reflection, methods can be treated as objects (everything is an object).
        Method method1 = (methodName);
        ("===================");

        //(4) Calling a method via method1: i.e., calling a method via a method object.
        (o);//Traditional methods Object. Method() , Reflection mechanism Method.invoke(object)

//: represents a member variable of a class, Field object represents a member variable of a class
//Get the name field
//getField can't get private properties, name is private, age is public.
        Field nameField = ("age");
        ((o));// Traditional way of writing Object. MemberVariable , Reflection : MemberVariable object.get(object)

//: represents the constructor method of a class, and the Constructor object represents the constructor.
//() can specify the type of constructor parameters, returning a constructor without parameters.
        Constructor constructor = ();
        (constructor);

        //What the teacher passed in here is the Class object of the String class.
        Constructor constructor2 = (String.class);
        (constructor2);
    }
}

Run results:

 

714, Reflection Call Optimization

Code:

The content of the document remains unchanged

package ;

public class Cat {
    private String name = "Fortune Cat";
    public int age = 10;

    public Cat() {} //unparameterized constructor

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

    public void hi() { //Common methods
//("hi " + name);
    }
}

 

package ;

import ;

import ;
import ;

//Testing the performance of reflection calls, and optimizations
public class Reflection02 {
    public static void main(String[] args) throws ClassNotFoundException, InvocationTargetException, InstantiationException, IllegalAccessException, NoSuchMethodException {
        m1();
        m2();
        m3();
    }

    //The traditional way to call hi
    public static void m1() {
        Cat cat = new Cat();
        long start = ();
        for (int i = 0; i < 90000000; i++) {
            ();
        }
        long end = ();
        ("Traditional method call hi Time consumed = " + (end - start));
    }

    //Reflection mechanism invokes method hi
    public static void m2() throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        Class cls = ("");//The parameter is given directly to the full class name (from the file)
        Object o = ();
        Method hi = ("hi");//The parameter is given directly to the method name (from the file)
        long start = ();
        for (int i = 0; i < 90000000; i++) {
            (o);
        }
        long end = ();
        ("m2() time consumed = " + (end - start));
    }

    //Reflection mechanism invokes method hi
    public static void m3() throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        Class cls = ("");//The parameter is given directly to the full class name (from the file)
        Object o = ();
        Method hi = ("hi");//The parameter is given directly to the method name (from the file)
        (true);//Remove access checking when calling a method by reflection.
        long start = ();
        for (int i = 0; i < 90000000; i++) {
            (o);
        }
        long end = ();
        ("m3() time consumed = " + (end - start));
    }
}

Run results:

 

716, Class Common Methods

 

Code:

package ;

public class Car {
    public String brand = "BMW";
    public int price = 500000;
    public String color = "white";

    @Override
    public String toString() {
        return "Car{" +
                "brand='" + brand + '\'' +
                ", price=" + price +
                ", color='" + color + '\'' +
                '}';
    }
}

 

 

package .class_;

import ;

import ;

public class Class02 {
    public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchFieldException {
        //1 . Get the corresponding Class object of the Car class
//<? > Indicates an indeterminate Java type.
        String classAllPath = "";
        Class<?> cls = (classAllPath);

        //2. Output cls
//Show cls object, which class is the Class object.
        (cls);
        //Output cls run type
        (());

        //3. Getting the package name
        (().getName());

        //4. Getting the full class name
        (());

        //5. Creating object instances via cls
        Car car = (Car)();
        (car);//()

        //6. Getting properties through reflection brand
        Field brand = ("brand");
        ((car));

        //7. Assigning values to properties through reflection
        (car, "Mercedes");
        ((car));

        //8 I want everyone to have access to all the attributes (fields)
        ("====== all field attributes ======="));
        Field[] fields = ();
        for (Field f : fields) {
            (());
        }
    }
}

 

Run results:

 

717, Six Ways to Get Class Objects

 

Code:

package .class_;

import ;

public class GetClass_ {
    public static void main(String[] args) throws ClassNotFoundException {
        //1. 
        //Get it by reading the configuration file
        String classAllPath = "";
        Class<?> cls1 = (classAllPath);
        (cls1);

        //2. class name.class , Application Scenario: used for parameter passing
        Class cls2 = Car.class;
        (cls2);

        //3. object.getClass(), application scenario, with object instances
        Car car = new Car();
        Class cls3 = ();
        (cls3);

        //4. 4 kinds of class loaders to get the class object of the class.
//(1) First get the class loader classLoader
        ClassLoader classLoader = ().getClassLoader();
        //(2) Getting Class Objects through Class Loader
        Class cls4 = (classAllPath);
        (cls4);

        //cls1 , cls2 , cls3 , cls4 are actually the same object.
        (());
        (());
        (());
        (());

        //5. Basic data (int, char, boolean, float, double, byte, long, short) Get the object of Class class as follows
        Class<Integer> integerClass = int.class;
        Class<Character> characterClass = char.class;
        Class<Boolean> booleanClass = boolean.class;
        (integerClass);//int

        //6. The corresponding wrapper class of the basic data type can be obtained from the Class object via .
        Class<Integer> type1 = ;
        Class<Character> type2 = ;
        (type1);

        (());
        (());
    }
}

 

Run results:

 

718, Which types have Class objects

 

Code:

package .class_;

import ;

public class AllTypeClass {
    public static void main(String[] args) {
        Class<String> cls1 = String.class;//external category
        Class<Serializable> cls2 = Serializable.class;//connector
        Class<Integer[]> cls3 = Integer[].class;//arrays
        Class<float[][]> cls4 = float[][].class;//two-dimensional array
        Class<Deprecated> cls5 = Deprecated.class;//explanatory note

        Class<> cls6 = .class;//enumeration
        Class<Long> cls7 = long.class;//fundamental data type
        Class<Void> cls8 = void.class;//void Data type
        Class<Class> cls9 = Class.class;

        (cls1);
        (cls2);
        (cls3);
        (cls4);
        (cls5);
        (cls6);
        (cls7);
        (cls8);
        (cls9);
    }
}

 

Run results:

 

725, Reflection Stormbreaker Creation Example

 

Code:

package ;

import ;
import ;

public class ReflecCreateInstance {
    public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException {
        //1. Get the Class object of the User class.
        Class<?> userClass = ("");

        //2. Creating instances through public referenceless constructors
        Object o = ();
        (o);

        //3. Creating instances through public parametric constructors
//3.1 Getting the corresponding constructor first
        Constructor<?> constructor = (String.class);
        //3.2 Creating instances and passing in real parameters
        Object hsp = ("hsp");
        ("hsp=" + hsp);

        //4. Creating instances via non-public parametric constructors
//4.1 Getting a private constructor object
        Constructor<?> constructor1 = (int.class, String.class);
        //4.2 Creating examples
//Breaking Bad, using reflection to access private constructors/methods/properties, Reflection is a paper tiger!
        (true);
        Object user2 = (100, "Zhang Sanfeng"));
        ("user2=" + user2);
    }
}
class User { //User class
    private int age = 10;
    private String name = "Han Soon Ping Education";

    public User() {//no-parameter public

    }

    public User(String name) {//public parametric constructor
        this.name = name;
    }

    private User(int age, String name) {//private Parametric constructor
        this.age = age;
        this.name = name;
    }
    @Override
    public String toString() {
        return "User{" +
                "age=" + age +
                ", name='" + name + '\'' +
                '}';
    }
}

 

Run results:

 

726, Reflective Storm Breaking Operational Attributes

 

Code:

package ;

import ;

public class ReflectAccessProperty {
    public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchFieldException {
        //1. Get the corresponding Class object of Student class
        Class<?> stuClass = ("");

        //2. Object creation
        Object o = ();
        //The runtime type of o is Student
        (());

        //3. Use reflection to get the age property object
        Field age = ("age");
        //Manipulating Properties via Reflection
        (o, 88);
        (o);
        //Returns the value of the age attribute
        ((o));

        //4. Use reflection to manipulate the name attribute
        Field name = ("name");
        //To break the name, you can manipulate the private attribute.
        (true);
        //Since name is a static attribute, o can also be written as null, (o, "Lao Han");
        (null, "Old Han");
        (o);
        ((o)); //Getting Property Values
        ((null));//Get the value of the attribute, name is required to be static.
    }
}
class Student {//resemble
    public int age;
    private static String name;

    public Student() {//constructor
    }

    public String toString() {
        return "Student [age=" + age + ", name=" + name + "]";
    }
}

 

Run results:

 

727, Reflective Storm Breaking Method of Operation

 

Code:

package ;

import ;
import ;

public class ReflecAccessMethod {
    public static void main(String[] args) throws NoSuchMethodException, InstantiationException, IllegalAccessException, ClassNotFoundException, InvocationTargetException {
        //1. Get the Class object of the Boss class.
        Class<?> bossCls = ("");

        //2. Object creation
        Object o = ();

        //3. call the public hi method
//Method hi = ("hi", );//OK
        //3.1 Getting the hi method object
        Method hi = ("hi", String.class);
        //3.2 Calling
        (o, "Han Soon-pyeong Education"));

        //4. Invoking private static methods
//4.1 Getting the say method object
        Method say = ("say", int.class, String.class, char.class);
        //4.2 Because the say method is private, it needs to be broken, using the same principles as the constructors and properties described earlier.
        (true);
        ((o, 100, "Zhang San", 'Male'));
        //4.3 Because the say method is static, it can also be called this way, by passing null
        ((null, 200, `Li Si', `Female'));

        //5. In reflection, if a method has a return value, it uniformly returns Object, but its runtime type is the same as the return type of the method definition.
        Object reVal = (null, 300, "Wang Wu", 'Male');
        ("run type of reVal = " + ());//String

        //In the case of demonstrating a return
        Method m1 = ("m1");
        Object reVal2 = (o);
        ("run type of reVal2 = " + ());//Monster
    }
}
class Monster {}
class Boss {//resemble
    public int age;
    private static String name;

    public Boss() {//constructor
    }

    public Monster m1() {
        return new Monster();
    }

    private static String say(int n, String s, char c) {//static method
        return n + " " + s + " " + c;
    }

    public void hi(String s) {//Common public methods
        ("hi " + s);
    }
}

 

Run results: