反射的使用的四步骤:
1 //加载DLL
Assembly assembly = Assembly.Load(“当前程序目录下的Dll名称”); Assembly assembly = Assembly.LoadFile(“完整的dLL路径”);
2 //获取类型信息
Type type =assembly.GetType(“dll名称.class”);
泛型类要使用占位符【`】再加上泛型的参数个数
Type type =assembly.GetType(“dll名称.class `3”);
指定泛型的参数类型
Type newType=type.MakeGenricType(new Type[] { type(int),typeof(string),typeof(dateTime)})
3 //创建对象
object oclass = Activator.CreateInstance(type);
//需要使用代入参数的方法
object oclass = Activator.CreateInstance(type,new object[] {参数1,参数2,参数3……});
4 //类型转换
Iclass iclass = (Iclass)oclass;
//使用反射调用方法 oclass创建的对象的实例
MethodInfo method = type.GetMethod("基本方法名称"); //无参数的方法
method.Invoke(oclass,null);
MethodInfo method = type.GetMethod("基本方法名称");
method.Invoke(oclass,new object[] {123}); //Int类型的参数
//静态函数的反射使用
MethodInfo method =type.GetMethod("Static方法名称");
method.Invoke(oclass,new object[] {"12323"}; //静态函数可以指定对象也可以不指定对象实例
method.Invoke(null,new object[] {"12323"};
//泛型类+泛型函数的反射使用
Type typeG = assembly.GetType("dll名称.类名 `1"); //获取类型信息 一个泛类
Type newTypeG = typeG.MakeGenericType(new Type[] {typeof(int)})
object oGenric = Activator.CreateInstance(newTypeG);
MethodInfo method = newTypeG.GetMethod(“泛型方法名”);
MethodInfo methodNew = method.MakeGenericMethod(new Type[] {typeof(int),typeof(string),typeof(Datetime)});
methodNew.Invoke(null,new object[] {123,"1234",DateTime.Now});
反射的优缺点
优点:反射提高了程序的灵活性和扩展性,降低耦合性,提高自适应能力。 它允许程序创建和控制任何类的对象,无需提前硬编码目标类;
缺点:
1、性能问题:使用反射基本上是一种解释操作,用于字段和方法接入时要远慢于直接代码。 因此反射机制主要应用在对灵活性和扩展性要求很高的系统框架上,普通程序不建议使用。
2.使用反射会模糊程序内内部逻辑:程序员希望在源代码中看到程序的逻辑, 反射等绕过了源代码的技术,因而会带来维护问题。反射代码比相应的直接代码更复杂。 至于执行效率的话,还可以,因为它是一种强类型语言,执行效率不错。
首先是性能:
反射包括了一些动态类型,所以JVM无法对这些代码进行优化。
因此,反射操作的效率要比那些非反射操作低得多。我们应该避免在经常被 执行的代码或
对性能要求很高的程序中使用反射。
|