Basic reflex:

Reflection is a dynamic Class processing mechanism, which is realized by Class Class.

Basic information about Class:

Module java.base
Package java.lang
    Class Class<T>
		java.lang.Object
 			java.lang.Class<T>
Copy the code

== There are three ways to get reflections from classes, all of which are very important to keep in mind. = =

  1. Get an instantiated Object using the getClass() method provided in the Object class
class Member {}
public class JavaReflectDemo {
	public static void main(String[] args) throws Exception {
		// We need to obtain the instantiated object of a Class before we can obtain an instance of a Class
		Member member = new Member() ;	// Instantiate the Member class objectClass<? > clazz = member.getClass() ;// Get the Class instantiated objectSystem.out.println(clazz); }}Copy the code
  1. Use the form “class.class”
class Member {}
public class JavaReflectDemo {
	public static void main(String[] args) throws Exception {
		// * * * * * * * * * * * * * * * * * * * * * * * * * *Class<? > clazz = Member.class ;// Get the Class instantiated objectSystem.out.println(clazz); }}Copy the code
  1. Get the instantiated object based on the full name of the Class using the forName() method provided internally by the Class Class
class Member {}
public class JavaReflectDemo {
	public static void main(String[] args) throws Exception {
		// [Operation features] By name string (package. Class) can get an instance of Class, which can be imported without using import
        // Get the Class instantiated objectClass<? > clazz = Class.forName("cn.xbhog.demo.Member"); System.out.println(clazz); }}Copy the code

Reflection to get instantiated objects:

packageCom.xbhog. Reflection mechanism;class Member{
    public Member(a) {	// The constructor
        System.out.println("[constructor] instantiates the Member class object.");
    }
    @Override
    public String toString(a) {
        return "[the toString () overwrite 】 blog: http://www.cnblogs.com/xbhog"; }}public classReflection get object{
    public static void main(String[] args) throws Exception {
        // Get the Class instantiated objectClass<? > clazz = Class.forName("Com.xbhog. Reflection mechanism. Member"); 	
        // The reflection mechanism can get any class instantiated Object (equivalent to the keyword "new"), so the type returned is Object
        Object obj = clazz.getDeclaredConstructor().newInstance() ;// Instantiate the objectSystem.out.println(obj); }}Copy the code

The mechanism of reflection makes it easier for developers to decouple and design;

Reflection and class operations:

Under the reflection mechanism, you can automatically obtain and call the constituent structure (member attributes, methods) in any class, making the coding more flexible.

Reflection gets the class structure:

packageCom.xbhog. Reflection mechanism;interface IMessage{
    public void send(a);
}
interface IChannelService{
    public Boolean connect(a);
}

abstract class AbstractBase{}
public class Mail extends AbstractBase implements IMessage.IChannelService{
    @Override
    public void send(a) {
        if(this.connect()){
            System.out.println("Message sent successfully"); }}@Override
    public Boolean connect(a) {
        return true; }}Copy the code
packageCom.xbhog. Reflection mechanism;public class MailTest {
    public static void main(String[] args) {
        Class<Mail> aClass = Mail.class;
        System.out.println(aClass.getPackage());  // Get the package name of the class
        Class<? super Mail> superclass = aClass.getSuperclass(); // Obtain information about the parent object
        System.out.println(superclass.getName());  // Get the name of the superclass
        System.out.println(superclass.getSuperclass().getName());  // Get the name of the superclass of the superclass

        /* Get interface information */Class<? >[] interfaces = aClass.getInterfaces();for(Class<? > anInterface : interfaces) { System.out.println(anInterface.getName()); }}}Copy the code

The reflection call constructor:

Reflection can also call constructors, which are an important part of a class and are the methods that must be called when an object is instantiated.

Example:

import java.lang.reflect.Constructor;
class Mail {
	private String msg ;
	public Mail(a) {}// Constructs with no parameters
	public Mail(String msg) {// Single-parameter structure
		System.out.println("[constructor] calls the Mail class single-argument constructor to instantiate the object.");
		this.msg = msg ;
	}
	@Override
	public String toString(a) {	// Object information
		return [toString() overridden] Message content: + this.msg; }}public class JavaReflectDemo {
	public static void main(String[] args) throws Exception { Class<? > cls = Mail.class ;// Get the Class object of the specified ClassConstructor<? >[] constructors = cls.getDeclaredConstructors() ;// Get all constructs
		for(Constructor<? > cons : constructors) { System.out.println(cons); }// Get an instance of a constructor object that takes a single argument and is of type StringConstructor<? > cons = cls.getDeclaredConstructor(String.class) ; Object obj = cons.newInstance("www.cnblog.cn/xbhog");// Call the single argument to construct the instantiated objectSystem.out.println(obj); }}Copy the code

Reflection call method:

The most important function of the reflection mechanism is to use the invoke() Method of the Method class and instantiate an Object (Object type) to achieve a radial call.

Reflect the setter and getter methods in the call class (emphasis)

packageCom.xbhog. Reflection mechanism. Methods;import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

class Member{
    private String name;
    public void setName(String name){
        this.name = name;

    }
    public String getName(a){
        return this.name; }}public class getter_Setter {
    public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException { Class<? > cls = Member.class; String value ="xbhog";
        // Instantiate the Member object
        Object obj = cls.getDeclaredConstructor().newInstance();
        // To call a method in reflection, you need to know the name of the method and the types of parameters in the method
        String setMethodName ="setName";
        Method setmethod = cls.getDeclaredMethod(setMethodName, String.class);  // Get the specified method
        setmethod.invoke(obj,value);  / / object. Elegantly-named setName (value)
        String getMethodName = "getName";
        Method getMethod = cls.getDeclaredMethod(getMethodName);  // Get has no arguments
        System.out.println(getMethod.invoke(obj));/ / object. The getName ();}}Copy the code

The most important feature of radially implemented method calls is that they can be called directly from an instantiated Object of type Object, but they need to know the name of the method and the parameter types of the method when obtaining the Object.

The Field class does:

In practice, the getType() method in the Field is often used to determine the type of the property

Example:

import java.lang.reflect.Field;

class Member{
    private String name;
    public void setName(String name){
        this.name = name;

    }
    public String getName(a){
        return this.name; }}public class FIeldDemo {
    public static void main(String[] args) throws Exception {
        // Get the Member classClass<? > cls = Member.class;/ / instantiate
        Object obj = cls.getDeclaredConstructor().newInstance();
        // The type of the member attribute name
        Field name = cls.getDeclaredField("name");
        // Get the details
        System.out.println(name.getType().getName());
        // Get brief informationSystem.out.println(name.getType().getSimpleName()); }}Copy the code

Results:

java.lang.String String