Table of Contents
Reflection" >Reflection
IOC" >IOC

Reflection and IOC

Feb 23, 2017 am 09:46 AM

Reflection

The reflection mechanism is in the running state. For any class, it can know all the attributes and properties of the class. Method; for any object, any of its methods can be called; this function of dynamically obtaining and dynamically calling the object's methods is called the reflection mechanism. The reflection mechanism dynamically obtains methods and uses them, which is completely different from directly creating an object of a class and calling it directly. For example, if there is a property or method in a class that is private, we cannot call it directly, but we can use the reflection mechanism to call it dynamically.

IOC

## The biggest benefit of IOC is that object generation is It is defined in XML, so when we need to change an implementation subclass, it will become very simple (generally such objects are implemented in some kind of interface), just modify the XML, so that we can even realize the hotness of the object. Plug and unplug (a bit like USB interface and SCSI hard drive). Before IOC is not applicable, if an object depends on another object (hereinafter we will refer to it as the dependent object and the dependent object), we must instantiate a dependent object in the dependent object so that the methods in the dependent object can be called. Obviously, this degree of coupling is relatively high and does not conform to our programming principles. Therefore, at this time we will introduce a third-party object, which is responsible for directly delivering a dependent object to the dependent object, reducing the coupling between the two. The following figure shows the comparison of object coupling in the system before and after adding the IOC container


## Before the IOC container was introduced in the software system, as shown in Figure 1, object A depends on object B. Then object A must actively create it when it is initialized or runs to a certain point. Object B or use an already created object B. Whether you are creating or using object B, the control is in your hands. After the IOC container was introduced into the software system, this situation completely changed. As shown in Figure 2, due to the addition of the IOC container, the direct connection between object A and object B was lost. Therefore, when object A runs to When object B is needed, the IOC container will actively create an object B and inject it into the location where object A is needed. Through the comparison before and after, it is not difficult to see that the process of object A becoming dependent on object B changes from active behavior to passive behavior, and the control rights are reversed. This is the origin of the name "inversion of control".


Instance

##Reflection instance code

<span style="font-family:KaiTi_GB2312;font-size:18px;color:#666666;"><strong>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace StudentDAL
{
    public class Student
    {
        //属性
        public string Name{get;set;}
        public int Age { get; set; }

        //无参数构造函数
        public Student()
        {
            this.Name = "无参数";
            this.Age = 0;

        }
        //有参数构造函数
        public Student(string name, int age)
        {
            this.Name = "name";
            this.Age = age;
        }

        //public带参带返回值函数
        public string PublishMethodReturn()
        {
            return string.Format("我叫"+Name+"年龄" +Age);
        }
    }
}</strong></span>
Copy after login
rrree



Running result



##IOC example code


#

<span style="font-family:KaiTi_GB2312;font-size:18px;color:#666666;"><strong>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;

namespace ITOO_Reflection
{
    class Program
    {
        static void Main(string[] args)
        {
            //使用 Assembly 定义和加载程序集,
            //加载在程序集清单中列出的模块,
            //以及从此程序集中查找类型并创建该类型的实例.
            //获取程序集
            Assembly assembly = Assembly.Load("StudentDAL");
            //从程序及获取指定对象类型
            Type type = assembly.GetType("StudentDAL.Student");
            var instance = assembly.CreateInstance("StudentDAL.Student");
            //为学生类的属性赋值
            type.GetProperty("Name").SetValue(instance, "shx", null);
            type.GetProperty("Age").SetValue(instance, 18, null);
            //获取Student类的方法
            var method = type.GetMethod("PublishMethodReturn");
            //调用Student类的成员方法PublishMethodReturn
            var S= method.Invoke(instance, null);
          
            Console.WriteLine(S);
            Console.Read();
        }
    }
}</strong></span>
Copy after login
<span style="font-family:KaiTi_GB2312;font-size:18px;color:#666666;"><strong>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ITOO.IOC.IDAL
{
    public interface IUserDal
    {
        void HelloWord();
    }
}
</strong></span>
Copy after login
<span style="font-family:KaiTi_GB2312;font-size:18px;color:#666666;"><strong>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ITOO.IOC.IDAL;

namespace ITOO.IOC.DAL
{
    public class User:IUserDal
    {
        public void HelloWord()
        {
            Console.WriteLine("helloword");
        }
    }
}
</strong></span>
Copy after login
<span style="font-family:KaiTi_GB2312;font-size:18px;color:#666666;"><strong>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ITOO.IOC.IBLL
{
    public interface IUserBll
    {
        void HelloWord();
    }
}
</strong></span>
Copy after login
<span style="font-family:KaiTi_GB2312;font-size:18px;color:#666666;"><strong>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ITOO.IOC.IBLL;
using ITOO.IOC.IDAL;
using ITOO.Library.Core.AOP;

namespace ITOO.IOC.BLL
{
    public class UserBll:IUserBll
    {
        public void HelloWord()
        {
            //使用底层封装的SpringHelper从IOC容器中拿到D层的类的对象实例
            IUserDal iuser = SpringHelper.GetObject<IUserDal>("User");
            iuser.HelloWord();
        }
    }
}
</strong></span>
Copy after login


operation result



The above is the content of reflection and IOC. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Reflection mechanism implementation of interfaces and abstract classes in Java Reflection mechanism implementation of interfaces and abstract classes in Java May 02, 2024 pm 05:18 PM

The reflection mechanism allows programs to obtain and modify class information at runtime. It can be used to implement reflection of interfaces and abstract classes: Interface reflection: obtain the interface reflection object through Class.forName() and access its metadata (name, method and field) . Reflection of abstract classes: Similar to interfaces, you can obtain the reflection object of an abstract class and access its metadata and non-abstract methods. Practical case: The reflection mechanism can be used to implement dynamic proxies, intercepting calls to interface methods at runtime by dynamically creating proxy classes.

How to use reflection to access private fields and methods in golang How to use reflection to access private fields and methods in golang May 03, 2024 pm 12:15 PM

You can use reflection to access private fields and methods in Go language: To access private fields: obtain the reflection value of the value through reflect.ValueOf(), then use FieldByName() to obtain the reflection value of the field, and call the String() method to print the value of the field . Call a private method: also obtain the reflection value of the value through reflect.ValueOf(), then use MethodByName() to obtain the reflection value of the method, and finally call the Call() method to execute the method. Practical case: Modify private field values ​​and call private methods through reflection to achieve object control and unit test coverage.

Security considerations and best solutions for golang reflection Security considerations and best solutions for golang reflection May 04, 2024 pm 04:48 PM

Reflection provides type checking and modification capabilities in Go, but it has security risks, including arbitrary code execution, type forgery, and data leakage. Best practices include limiting reflective permissions, operations, using whitelists or blacklists, validating input, and using security tools. In practice, reflection can be safely used to inspect type information.

How to use reflection to dynamically modify variable values ​​in golang How to use reflection to dynamically modify variable values ​​in golang May 02, 2024 am 11:09 AM

Go language reflection allows you to manipulate variable values ​​at runtime, including modifying Boolean values, integers, floating point numbers, and strings. By getting the Value of a variable, you can call the SetBool, SetInt, SetFloat and SetString methods to modify it. For example, you can parse a JSON string into a structure and then use reflection to modify the values ​​of the structure fields. It should be noted that the reflection operation is slow and unmodifiable fields cannot be modified. When modifying the structure field value, the related fields may not be automatically updated.

Introduction to Golang reflection and analysis of application scenarios Introduction to Golang reflection and analysis of application scenarios Apr 03, 2024 pm 01:45 PM

The reflection feature in the Go language allows a program to inspect and modify the structure of a type at runtime. By using Type, Value and reflect.Kind, we can obtain the type information, field values ​​and methods of the object, and we can also create and modify objects. Specific operation methods include: checking type (TypeOf()), obtaining field value (ValueOf(), FieldByName()), modifying field value (Set()), and creating object (New()).

Implementation and practice of IOC in Go language: Detailed explanation of inversion of control Implementation and practice of IOC in Go language: Detailed explanation of inversion of control Apr 07, 2024 pm 02:33 PM

Inversion of control is a design pattern that moves object creation and dependency management from client code to the container, improving code flexibility and testability. The implementation of IOC in Go language can use the wire framework. The specific steps include: defining interfaces, defining types, and using wire functions. By using wire-generated containers, you can gain the advantages of improved testability, flexibility, and simplified configuration.

How to use reflection to create new types in golang How to use reflection to create new types in golang May 01, 2024 am 09:21 AM

Using reflection, Go allows the creation of new types. 1. Use reflect.TypeOf() to get the reflect.Type value of an existing type; 2. Use reflect.New() to create a pointer value of a new type; 3. Through *Ptr.Elem( ) to access the actual value; 4. Reflection can also dynamically create new types based on strings, which is used to build flexible and dynamic programs.

Using Java reflection mechanism for method overloading? Using Java reflection mechanism for method overloading? Apr 15, 2024 pm 10:54 PM

The reflection mechanism is used in Java to implement method overloading: Obtain methods through reflection: Use the getMethod() method to obtain the method object and specify the method name and parameter type. Calling method: Use the invoke() method to call the method, specifying the caller object and parameter values.

See all articles