C# Type.GetConstructor() 根据构造函数参数获取实例对象(一)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Kernel.Interface
{
    public interface IObjcet
    {
        void Put();

        void Put(string plus);
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Kernel.Interface;

namespace Kernel.SimpleLibrary
{
    public class PlugPut : IObjcet
    {

        private string plugName = "my plugName value is default!";

        public string PlugName
        {
            get { return plugName; }
            set { plugName = value; }
        }

        public PlugPut() { }
             

        public PlugPut(string plusName) 
        {
            this.PlugName = plusName;
        }

        public void Put()
        {
            Console.WriteLine("Default plug value is:" + plugName);
        }

        public void Put(string plus)
        {
            Console.WriteLine("Put plus value is:" + plus);
        }
    }
}
using Kernel.DriverLibrary;
using Kernel.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Kernel.TypeLibrary
{
    public class TypeHelper
    {
        public static object CreateObject<T>(params object[] args) where T : IObjcet
        {
            try
            {
                Type myType = typeof(T);

                int lenght = 0;
                if (args != null)
                {
                    lenght = args.Length;
                }

                Type[] types = new Type[lenght];
                for (int i = 0; i < args.Length; i++)
                {
                    types[i] = args[i].GetType();
                }

                object[] param = new object[lenght];
                for (int i = 0; i < args.Length; i++)
                {
                    param[i] = args[i];
                }

                object obj = null;

                // Get the constructor that takes an integer as a parameter.
                ConstructorInfo constructorInfoObj = myType.GetConstructor(types);

                //ConstructorInfo constructorInfoObj = myType.GetConstructor(BindingFlags.Instance | BindingFlags.Public,
                //                                                    null, types, null);
                //ConstructorInfo constructorInfoObj = myType.GetConstructor(BindingFlags.Instance | BindingFlags.Public, 
                //                                                null,CallingConventions.HasThis, types, null);

                //CustomBinder customBinder = new CustomBinder();
                //ConstructorInfo constructorInfoObj = myType.GetConstructor(BindingFlags.Instance | BindingFlags.Public, 
                //                                                customBinder, CallingConventions.HasThis, types, null);

                if (constructorInfoObj != null)
                {
                    Console.WriteLine("The constructor of PlugPut that takes an integer as a parameter is: " 
                  + constructorInfoObj.ToString()); //Console.WriteLine(constructorInfoObj.ToString()); //调用指定参数的构造函数 obj = constructorInfoObj.Invoke(param); } else { Console.WriteLine("The constructor of PlugPut that takes an integer as a parameter is not available."); //myType is System.Type.GetType("Kernel.SimpleLibrary.PlugPut,Kernel.SimpleLibrary") //Activator.CreateInstance(System.Type.GetType("Kernel.SimpleLibrary.PlugPut,Kernel.SimpleLibrary"), null); obj = Activator.CreateInstance(myType, null); } return obj; } catch (Exception) { throw; } } } }
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Kernel.DriverLibrary
{
    public class CustomBinder : Binder
    {
        public override MethodBase BindToMethod(
            BindingFlags bindingAttr,
            MethodBase[] match,
            ref object[] args,
            ParameterModifier[] modifiers,
            CultureInfo culture,
            string[] names,
            out object state)
        {
            if (match == null)
            {
                throw new ArgumentNullException("match");
            }
            // Arguments are not being reordered.
            state = null;
            // Find a parameter match and return the first method with
            // parameters that match the request.
            foreach (MethodBase mb in match)
            {
                ParameterInfo[] parameters = mb.GetParameters();

                if (ParametersMatch(parameters, args))
                {
                    return mb;
                }
            }
            return null;
        }

        public override FieldInfo BindToField(BindingFlags bindingAttr,
            FieldInfo[] match, object value, CultureInfo culture)
        {
            if (match == null)
            {
                throw new ArgumentNullException("match");
            }
            foreach (FieldInfo fi in match)
            {
                if (fi.GetType() == value.GetType())
                {
                    return fi;
                }
            }
            return null;
        }

        public override MethodBase SelectMethod(
            BindingFlags bindingAttr,
            MethodBase[] match,
            Type[] types,
            ParameterModifier[] modifiers)
        {
            if (match == null)
            {
                throw new ArgumentNullException("match");
            }

            // Find a parameter match and return the first method with
            // parameters that match the request.
            foreach (MethodBase mb in match)
            {
                ParameterInfo[] parameters = mb.GetParameters();
                if (ParametersMatch(parameters, types))
                {
                    return mb;
                }
            }

            return null;
        }

        public override PropertyInfo SelectProperty(
            BindingFlags bindingAttr,
            PropertyInfo[] match,
            Type returnType,
            Type[] indexes,
            ParameterModifier[] modifiers)
        {
            if (match == null)
            {
                throw new ArgumentNullException("match");
            }
            foreach (PropertyInfo pi in match)
            {
                if (pi.GetType() == returnType &&
                    ParametersMatch(pi.GetIndexParameters(), indexes))
                {
                    return pi;
                }
            }
            return null;
        }

        public override object ChangeType(
            object value,
            Type myChangeType,
            CultureInfo culture)
        {
            try
            {
                object newType;
                newType = Convert.ChangeType(value, myChangeType);
                return newType;
            }
            // Throw an InvalidCastException if the conversion cannot
            // be done by the Convert.ChangeType method.
            catch (InvalidCastException)
            {
                return null;
            }
        }

        public override void ReorderArgumentArray(ref object[] args,
            object state)
        {
            // No operation is needed here because BindToMethod does not
            // reorder the args array. The most common implementation
            // of this method is shown below.

            // ((BinderState)state).args.CopyTo(args, 0);
        }

        // Returns true only if the type of each object in a matches
        // the type of each corresponding object in b.
        private bool ParametersMatch(ParameterInfo[] a, object[] b)
        {
            if (a.Length != b.Length)
            {
                return false;
            }
            for (int i = 0; i < a.Length; i++)
            {
                if (a[i].ParameterType != b[i].GetType())
                {
                    return false;
                }
            }
            return true;
        }

        // Returns true only if the type of each object in a matches
        // the type of each corresponding entry in b.
        private bool ParametersMatch(ParameterInfo[] a, Type[] b)
        {
            if (a.Length != b.Length)
            {
                return false;
            }
            for (int i = 0; i < a.Length; i++)
            {
                if (a[i].ParameterType != b[i])
                {
                    return false;
                }
            }
            return true;
        }
    }
}
using Kernel.DriverLibrary;
using Kernel.Interface;
using Kernel.SimpleLibrary;
using Kernel.TypeLibrary;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.Remoting;
using System.Text;
using System.Threading.Tasks;

namespace Kernel.App
{
    class Program
    {
        static void Main(string[] args)
        {
            #region
            Console.Write("Put plus value is:");
            string strPlus = Console.ReadLine();

            //无参构造函数
            IObjcet obj = (IObjcet)TypeHelper.CreateObject<PlugPut>();
            obj.Put();
            obj.Put(strPlus);

            //定义构造函数所需参数
            object[] param = new object[1];
            param[0] = strPlus;

            //带参数的构造函数
            obj = (IObjcet)TypeHelper.CreateObject<PlugPut>(param);
            obj.Put();
            obj.Put(strPlus);

            #endregion

            Console.ReadLine();
        }
    }
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在 Java 9 及更高版本中,可以使用 `clazz.getConstructor(Class<?>... parameterTypes)` 方法来获取指定参数类型的构造函数。该方法的参数是一个可变参数,用于指定构造函数参数类型。 以下是一个使用 `getConstructor()` 方法获取构造函数的示例: ```java import java.lang.reflect.Constructor; public class ReflectionDemo { public static void main(String[] args) { try { // 获取类的信息 Class<MyClass> clazz = MyClass.class; // 获取指定参数类型的构造函数 Constructor<MyClass> constructor = clazz.getConstructor(String.class, int.class); // 使用构造函数实例对象 MyClass obj = constructor.newInstance("Example", 10); // 调用对象的方法 obj.printInfo(); } catch (Exception e) { e.printStackTrace(); } } } class MyClass { private String name; private int age; public MyClass(String name, int age) { this.name = name; this.age = age; } public void printInfo() { System.out.println("Name: " + name); System.out.println("Age: " + age); } } ``` 在上述示例中,使用 `getConstructor(String.class, int.class)` 获取具有 `String` 和 `int` 参数类型的构造函数,然后使用 `newInstance()` 方法来实例化 `MyClass` 对象,并传入参数值 "Example" 和 10。最后调用对象的 `printInfo()` 方法打印对象的信息。 请注意,该示例仅适用于 Java 9 及更高版本,因为在 Java 8 及更早的版本中,`getConstructor()` 方法只接受一个参数 `Class<?>[] parameterTypes`,而不是可变参数

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值