得到字节码的三种方法:
1: Class.forName("类名") (反射主要用这个)
2:对象.getClass()
3: 类名.class
二: Constructor类代表某个类中的一个构造方法
得到某个类所有的构造方法 Class.forName("java.lang.String").getConstructor();
(注意用参数类型来判断调用哪个构造方法)
得到某一个构造方法 Class.forName("java.lang.String").getConstructor(StringBuffer.class);
创建实例对象
反射方式: String str = (String)constructor.newInstance(new StringBuffer("abc"));
(调用获得的方法时要用到上面相同类型的实例对象)
Class.newInstance()方法
三:Field类代表某个类中的一个成员变量
四:Method类代表某个类中的一个成员方法
如果传递给Method对象的invoke()方法的第一个参数为null,说明该Method对对应的是一个静态方法!
获取页面类的类型
Type compiledType = null;
try {
//Compiles a file given its virtual path and returns the compiled type.
compiledType = BuildManager.GetCompiledType(virtualPath);
if (compiledType == null){
//Processes a file given its virtual path and creates an instance of the result.
object page = BuildManager.CreateInstanceFromVirtualPath(virtualPath, typeof(System.Web.UI.Page));
compiledType = page.GetType();
}
}
if (_pageMethods) flags |= BindingFlags.Static;
else flags |= BindingFlags.Instance;
MethodInfo methodInfo = typeList[i].GetMethods(flags);
object target = null ;
if ( ! _methodInfo.IsStatic) target = Activator.CreateInstance(methodData.Owner.TypeData.Type);
_methodInfo.Invoke(target, actualParams);
object obj = System.Activator.CreateInstance(t);
MethodInfo mif = t.GetMethod("Show");
mif.Invoke(obj, null); // or ((Form)obj).Show();
创建对象
1、
Assembly assembly = Assembly.Load("A") ;A为程序集名称
Type t= assembly.GetType("A.B.C", true, true) ;A.B.C为类的全称
// 动态创建实例
object obj = Activator.CreateInstance (t);
2、
System.Reflection.Assembly ass = System.Reflection.Assembly.Load(nameSpace);
object obj = ass.CreateInstance(className);
Iobject op = (Iobject)obj; // Iobject为抽象类,是className的父类
3、
using System.Reflection;
Assembly assembly = Assembly.LoadFrom("xxx.dll的路径");
Type[] aa = a.GetTypes();
foreach(Type t in aa)
... {
if(t.FullName == "a.b.c")
...{
object o = Activator.CreateInstance(t);
}
}