JAVA basic "reflection"

preface Reflection mechanism What is reflection? Reflection is to know all the properties and methods of any class in th...
Introduction to reflection
Three ways to get Class objects
Reflection gets the construction method and uses it
Reflection get member variable
Reflection get member method

preface

Reflection mechanism

What is reflection?
Reflection is to know all the properties and methods of any class in the running state; For any object, you can call any of its methods and properties; This kind of dynamically obtained information and the function of dynamically calling object methods are called the reflection mechanism of Java language.

Where is the reflection mechanism used?
1. In JDBC, the database driver is dynamically loaded by reflection.
2. The service method of Sevlet is called by reflection in the web server.
3.Eclispe and other development tools use reflection to dynamically analyze the type and structure of objects and dynamically prompt the attributes and methods of objects.
4. Many frameworks use reflection mechanism, inject attributes and call methods, such as Spring

Advantages and disadvantages of reflection mechanism?
Advantages: it can be executed dynamically. During operation, it can dynamically execute methods and access properties according to business functions, giving full play to the flexibility of java.
Disadvantages: it has an impact on performance. Such operations are always slower than direct execution of java code

What is the role of Java reflection mechanism?
1. Judge the class of any object at run time
2. Construct the object of any class at runtime
3. Judge the member variables and methods of any class at run time
4. Call the method of any object at run time

Through the understanding of the above questions and answers, I believe many small partners have some questions about reflection. Take the questions to learn reflection and get twice the result with half the effort!!!!

reflex

Introduction to reflection

It refers to obtaining the variable and method information of a class at run time. Then create an object through the obtained information and call a mechanism of the method. Because of this dynamic, it can greatly enhance the flexibility of the program. The program does not need to be determined at the compilation time, and can still be extended at the run time.

Three ways to get Class objects

Three ways

  • class name. class attribute
  • Object name. getClass() method
  • Class. Forname (full class name) method
    Example code:
//Use the class attribute of the class to get the class object corresponding to the class Class<Student> c1 = Student.class; System.out.println(c1); //Call the getClass() method of the object to return the Class object corresponding to the Class to which the object belongs Student s = new Student(); Class<? extends Student> c2 = s.getClass(); //Use the static method forName(String className) in Class Class<?> c3 = Class.forName("com.itheima_02.Student");

Reflection gets the construction method and uses it

Class gets the method of constructing the method object

Method nameexplainConstructor<?>[] getConstructors()Returns an array of all public constructor objectsConstructor<?>[] getDeclaredConstructors()Returns an array of all constructor objectsConstructor getConstructor(Class<?>... parameterTypes)Returns a single common constructor objectConstructor getDeclaredConstructor(Class<?>... parameterTypes)Returns a single constructor object

Constructor class is the method used to create objects

Method nameexplainT newInstance(Object...initargs)Creates an object according to the specified construction method

Example code:

Class<?> c = Class.forName("com.itheima_02.Student"); //Constructor<?> [] getconstructors() returns an array containing the constructor object, which reflects all public constructors of the Class represented by the Class object Constructor<?>[] cons = c.getConstructors(); //Constructor<?> [] getdeclaredconstructors() returns an array of constructor objects that reflect all constructors declared by the Class represented by the Class object Constructor<?>[] cons = c.getDeclaredConstructors(); for(Constructor con : cons) { System.out.println(con); } System.out.println("--------"); //Constructor < T > getconstructor (Class <? >... Parametertypes) returns a constructor object that reflects the specified public constructor of the Class represented by the Class object //Constructor < T > getdeclaraedconstructor (Class <? >... Parametertypes) returns a constructor object that reflects the specified constructor of the Class or interface represented by this Class object //Parameters: the number of parameters of the constructor you want to obtain and the bytecode file object corresponding to the data type Constructor<?> con = c.getConstructor(); //Constructor provides information and access rights for a single constructor of a class //T newInstance(Object... initargs) uses the Constructor represented by this Constructor object and uses the specified initialization parameters to create and initialize a new instance of the declaration class of the Constructor Object obj = con.newInstance(); System.out.println(obj); // Student s = new Student(); // System.out.println(s);

Reflection get member variable

Class gets the method of the member variable object

Method nameexplainField[] getFields()Returns an array of all public member variable objectsField[] getDeclaredFields()Returns an array of all member variable objectsField getField(String name)Returns a single public member variable objectField getDeclaredField(String name)Returns a single member variable object

The Field class is used to assign values to member variables

Method nameexplainvoidset(Object obj,Object value)Assign value to the member variable of obj object

Example code:

public class ReflectDemo01 { public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { //Get Class object Class<?> c = Class.forName("com.itheima_02.Student"); //Field[] getFields() returns an array containing field objects that reflect all accessible public fields of the Class or interface represented by the Class object //Field [] getdeclaraedfields() returns an array of field objects, reflecting all fields declared by the Class or interface represented by the Class object // Field[] fields = c.getFields(); Field[] fields = c.getDeclaredFields(); for(Field field : fields) { System.out.println(field); } System.out.println("--------"); //Field getField(String name) returns a field object that reflects the specified public member field of the Class or interface represented by the Class object //Field getdeclaraedfield (string name) returns a field object that reflects the specified declaration field of the Class or interface represented by the Class object Field addressField = c.getField("address"); //Gets the object created by the parameterless constructor Constructor<?> con = c.getConstructor(); Object obj = con.newInstance(); // obj.addressField = "Xi'an"; //Field provides information and dynamic access about a single field of a class or interface //void set(Object obj, Object value) sets the Field represented by this Field object in the specified object parameter to the specified new value addressField.set(obj,"Xi'an"); //Assign addressField to obj's member variable System.out.println(obj); // Student s = new Student(); // s.address = "Xi'an"; // System.out.println(s); } }

Reflection get member method

Class gets the method of the member method object

Method nameexplainMethod[] getMethods()Returns an array of all public member method objects, including inheritedMethod[] getDeclaredMethods()Returns an array of all member method objects, excluding inheritedMethod getMethod(String name, Class<?>... parameterTypes)Returns a single public member method objectMethod getDeclaredMethod(String name, Class<?>... parameterTypes)Returns a single member method object

The Method class is used to execute the Method

Method nameexplainObjectinvoke(Object obj,Object... args)Call the member method of obj Object. The parameter is args and the return value is Object type

Example code:

public class ReflectDemo01 { public static void main(String[] args) throws Exception { //Get Class object Class<?> c = Class.forName("com.itheima_02.Student"); //Method[] getMethods() returns an array containing method objects that reflect all public methods of the Class or interface represented by the Class object, including objects declared by the Class or interface and classes inherited from superclasses and superinterfaces //Method[] getDeclaredMethods() returns an array containing method objects that reflect all declared methods of the Class or interface represented by the Class object, including public, protected, default (package) access and private methods, but excluding inherited methods // Method[] methods = c.getMethods(); Method[] methods = c.getDeclaredMethods(); for(Method method : methods) { System.out.println(method); } System.out.println("--------"); //Method getmethod (string name, Class <? >... Parametertypes) returns a method object that reflects the specified public member methods of the Class or interface represented by the Class object //Method getdeclaraedmethod (string name, Class <? >... Parametertypes) returns a method object that reflects the specified declared method Class object of the represented Class or interface //public void method1() Method m = c.getMethod("method1"); //Gets the object created by the parameterless constructor Constructor<?> con = c.getConstructor(); Object obj = con.newInstance(); // obj.m(); //Provides information and access to a single method on a class or interface //Object invoke(Object obj, Object... args) calls the base method represented by this method object on the specified object with the specified parameters //Object: return value type //obj: the object that calls the method //args: parameter required by method m.invoke(obj); // Student s = new Student(); // s.method1(); } }

11 November 2021, 03:08 | Views: 3223

Add new comment

For adding a comment, please log in
or create account

0 comments