Java Foundation Review - Reflection

Introduction:

From sophomore's first contact with java, to understand its basic grammar, to use swing to write graphical interface programs, to Java Web with SSH three frameworks to write small websites, followed by SSM, Spring Boot, Spring Cloud and so on. It can be said that it is also a constant understanding of java, slowly into the big pit of java, feel good. Although there are more and more things to learn, it is necessary to review the next basics from time to time.

Summary:

The concept of reflection:

Reflection library provides a very rich and well-designed toolkit for writing programs that can dynamically manipulate Java code. This function is widely used in JavaBeans, which is the architecture of Java components. With reflection, Java can support tools that Visual Basic users are used to. Especially when adding new classes in design or running, it can quickly apply the ability of development tools to dynamically query new added classes. Programs that can analyze class capabilities are called reflectives. The function of reflection mechanism is extremely powerful.

The reflection mechanism can be used to:

The ability to analyze classes in operation.
Viewing objects at runtime, for example, writing a toString method for all classes.
Implementing the operation code of the array.
Using Method object, this object is very similar to function pointer in C++.

—— Java Core Technology Volume 1, Eighth Edition

A simpler description:

Reflection: Encapsulate the components of a class into other objects. (Other objects refer to Class class objects)

 

Reflection:

Three methods for obtaining word Class objects:

The stages Java code goes through in a computer:

Different acquisition methods are corresponded in three stages:

Source code stage: Class.forName("full class name");

It is mostly used for configuration files.

static Class<?>    forName(String className)
//Returns the Class object associated with the class or interface with the given string name.
static Class<?>    forName(String name, boolean initialize, ClassLoader loader)
//Returns the Class object associated with the class or interface with the given string name, using the given class loader.

Class class object stage: class name.

It is mostly used for data transmission.

java.lang.Object java.lang.Class<T>
/*
 *Type Parameters:
 *T - the type of the class modeled by this Class object.
 *For example, the type of String.class is Class<String>.
 * Use Class<?> if the class being modeled is unknown.
 */

Runtime phase: object. getClass();

Class<?>    getClass()
//Returns the runtime class of this Object.

Note: The same bytecode file (*. class) will only be loaded once during a program run, regardless of which way of getting lass objects.

Class Object Common Method (java.lang.Class):

Class object obtains member variables:

Get public member variables:

Field    getField(String name)
//Returns a Field object that reflects the specified public member field of the class or interface represented by this Class object.
Field[]    getFields()
//Returns an array containing Field objects 
//reflecting all the accessible public fields of the class or interface represented by this Class object.

Get all member variables under this class:

Field    getDeclaredField(String name)
//Returns a Field object that reflects the specified declared field of the class or interface represented by this Class object.
Field[]    getDeclaredFields()
//Returns an array of Field objects reflecting all the fields declared by the class or interface represented by this Class object. 

Class object acquisition construction method:

Acquisition of public construction methods

Constructor<T>    getConstructor(Class<?>... parameterTypes)
//Returns a Constructor object that reflects the specified public constructor of the class represented by this Class object.
Constructor<?>[]    getConstructors()
//Returns an array containing Constructorobjects reflecting all 
//the public constructors of the class represented by this Class object.

Get all constructions under this class

Constructor<T>    getDeclaredConstructor(Class<?>... parameterTypes)
//Returns a Constructor object that reflects the specified constructor of the class or interface represented by this Class object.
Constructor<?>[]    getDeclaredConstructors()
//Returns an array of Constructor objects reflecting all the constructors declared by the class represented by this Class object.

 

Class object acquisition member method:

Access to public membership methods:

Method    getMethod(String name, Class<?>... parameterTypes)
//Returns a Method object that reflects the specified public member method of the class or interface represented by this Class object.
Method[]    getMethods()
//Returns an array containing Method objects reflecting all the public member methods of the class or interface represented by this Class object,
//including those declared by the class or interface and those inherited from superclasses and superinterfaces.

Get all member methods:

Method[]    getDeclaredMethods()
//Returns an array of Method objects reflecting all the methods declared by the class or interface represented by this Class object.
Class<?>    getDeclaringClass()
//If the class or interface represented by this Class object is a member of another class, returns the Class object representing the class in which it was declared.

 

Class objects get other information:

int    getModifiers()
// Get modifiers
// Digital form public, protected, private, final, static, abstract and interface; 
// Callable Modifier Class method converts it into recognizable character representation
// Returns the Java language modifiers for this class or interface, 
// encoded in an integer.

String    getName()
// Get the class name( eg:java.lang.String)
// Returns the name of the entity (class, interface, array class, primitive type, or void) 
// represented by this Class object, as a String.

String    getSimpleName()
//  Get a simple class name
// Returns the simple name of the underlying class as given in the source code.

T    newInstance()
// A parametric-free construction method for creating this class
// Creates a new instance of the class represented by this Class object.

Package    getPackage()
// Getting packages
// Gets the package for this class.

Note (Access to content without access rights):

Setting security checks that ignore access permission modifiers

public static void setAccessible(AccessibleObject[] array,
                 boolean flag) throws SecurityException
/*
 *Convenience method to set the accessible flag for an array of objects with a  
 *single security check (for efficiency).
 *First, if there is a security manager, its checkPermission method is called with a  
 *ReflectPermission("suppressAccessChecks") permission.
 *
 *A SecurityException is raised if flag is true but accessibility of any of the  
 *elements of the input array may not be changed (for example, if the element  
 *object is a Constructor object for the class Class). In the event of such a  
 *SecurityException, the accessibility of objects is set to flag for array elements  
 *upto (and excluding) the element for which the exception occurred; the  
 *accessibility of elements beyond (and including) the element for which the  
 *exception occurred is unchanged.
 */

 

Field Object Common Method (java.lang.reflect.Field):

Object    get(Object obj)
// Obtain field value
// Returns the value of the field represented by this Field, on the specified object.

void    set(Object obj, Object value)
// Set up field value
// Sets the field represented by this Field object on the specified object argument to the specified new value.

Constructor object commonly used methods (java.lang.reflect.Constructor):

T    newInstance(Object... initargs)
// create object
// Uses the constructor represented by this Constructor object 
// to create and initialize a new instance of the constructor's declaring class, 
// with the specified initialization parameters.

Method Object Common Method (java.lang.reflect.Method):

Object    invoke(Object obj, Object... args)
// Call the current Method Methods in Objects
// Invokes the underlying method represented by this Method object,
// on the specified object with the specified parameters.

 

Reflection cases (Tool classes that create arbitrary class objects and execute any of their methods through reflection writing):

demo.properties

className=demo.Student
methodName=listen

ReflectDemo

**
 * @ClassName demo.ReflectDemo
 * @Description TODO
 * @Author flytree
 * @Date 2019/9/3 19:48
 */
public class ReflectDemo {
    public static void main(String[] args) throws Exception {
        // 1.Loading configuration files
        Properties properties = new Properties();
        // 1.1 Establish Properties object
        // 1.2 Load the configuration file and convert it to a collection
        // 1.2.1 Obtain class Configuration files in directories
        ClassLoader classLoader = ReflectDemo.class.getClassLoader();
        InputStream stream = classLoader.getResourceAsStream("demo.properties");
        properties.load(stream);

        // 2.Get the data defined in the configuration file
        String className = properties.getProperty("className");
        String methodName = properties.getProperty("methodName");

        // 3.Loading this class into memory
        Class cls = Class.forName(className);
        // 4.create object
        Object obj = cls.newInstance();
        // 5.Acquisition Method Object
        Method method = cls.getMethod(methodName);
        // 6.Execution method
        method.invoke(obj);
    }
}

 

Reference

JavaAPI: api=jdk_7u4

Tags: Java Spring ssh

Posted on Thu, 05 Sep 2019 01:00:07 -0700 by pollysal