Home >Java >javaTutorial >What are assembly loading and reflection mechanisms in Java?

What are assembly loading and reflection mechanisms in Java?

王林
王林forward
2023-05-07 13:25:07735browse

1. Assembly loading

When the JIT compiler compiles the IL code into local code, it will check which types are referenced in the IL code. During runtime, the JIT compiler uses the assembly's TypeRef and AssemblyRef metadata tables to determine which assembly defines the referenced type. The JIT compiler then loads the corresponding assembly into the AppDomain. Internally, the CLR uses System The static method Load of the .Reflection.Assembly class attempts to load an assembly. However, if we want to dynamically load an assembly, we can use Assembly's Load method to dynamically load the assembly. The Assembly class also provides other loading assembly methods, including LoadFrom(string path), LoadFile(stringassemblyFile), etc.

2. Reflection mechanism

Reflection in .net parses the metadata in the assembly during running and obtains the members of the type (including fields and constructors) , methods, properties, events, etc.) information.

Dynamicly load an assembly and obtain members of the type

Put the following class in a class library project, and compile and generate the assembly (for example, ClassLibrary1.dll, assuming that the dll Place it under the root directory of drive D)

public class ReflectTestClass    {       public  string name;       public int age;       public string Name       {           get { return name; }           set { name = value; }       }        public int Age       {           get { return age; }           set { age = value; }       }         /// <summary>        /// No Paramter Constructor        /// </summary>       public ReflectTestClass()       {        }         /// <summary>        /// Constructor with Parameter        /// </summary>        /// <param name="name"></param>        /// <param name="age"></param>        public ReflectTestClass(string names,int ages)        {            this.name = names;            this.age = ages;        }         public string writeString(string name)        {            return "Welcome " + name;        }         public static string WriteName(string name)        {            return "Welcome "+name +" Come here";        }         public string WirteNopara()        {            return "The method is no parameter ";        }    }

Then create a console program to dynamically load the assembly generated above and members of the output type. Detailed introduction is in the code.

class Program     {         static void Main(string[] args)         {             Assembly ass;             Type[] types;             Type typeA;             object obj;             try             {                 // 从本地中 加载程序集 然后从程序集中通过反射获得类型的信息的,并且调用方法                 ass = Assembly.LoadFrom(@"D:\ClassLibrary1.dll");                 types = ass.GetTypes();                 foreach (Type type in types)                 {                     Console.WriteLine("Class Name is " + type.FullName);                     Console.WriteLine("Constructor Information");                     Console.WriteLine("-----------------------");                     // 获取类型的结构信息                     ConstructorInfo[] myconstructors = type.GetConstructors();                     ShowMessage<ConstructorInfo>(myconstructors);                      Console.WriteLine("Fields Information");                     Console.WriteLine("-----------------------");                     // 获取类型的字段信息                     FieldInfo[] myfields = type.GetFields();                     ShowMessage<FieldInfo>(myfields);                      Console.WriteLine("All Methods Information");                     Console.WriteLine("-----------------------");                     // 获取方法信息                     MethodInfo[] myMethodInfo = type.GetMethods();                     ShowMessage<MethodInfo>(myMethodInfo);                      Console.WriteLine("All Properties Information");                     Console.WriteLine("-----------------------");                     // 获取属性信息                     PropertyInfo[] myproperties = type.GetProperties();                     ShowMessage<PropertyInfo>(myproperties);                 }                  // 用命名空间+类名获取类型                 typeA = ass.GetType("ClassLibrary1.ReflectTestClass");                                  // 获得方法名称                  MethodInfo method = typeA.GetMethod("writeString");                  // 创建实例                 obj = ass.CreateInstance("ClassLibrary1.ReflectTestClass");                  string result = (String)method.Invoke(obj,new string[] {"Tom"});                 Console.WriteLine("Invoke Method With Parameter");                 Console.WriteLine("-----------------------");                 Console.WriteLine(result);                 Console.WriteLine("-----------------------");                 Console.WriteLine();                 method = typeA.GetMethod("WriteName");                 result = (string)method.Invoke(null,new string[] {"Tom"});                 Console.WriteLine("Invoke Static Method with Parameter");                 Console.WriteLine("-----------------------");                 Console.WriteLine(result);                 Console.WriteLine("-----------------------");                 Console.WriteLine();                 method = typeA.GetMethod("WirteNopara");                 Console.WriteLine("Invoke Method with NOParameter");                 result = (string)method.Invoke(obj, null);                 Console.WriteLine("-----------------------");                 Console.WriteLine(result);                 Console.WriteLine("-----------------------");             }              catch(FileNotFoundException ex)             {                 Console.WriteLine(ex.Message);             }              Console.ReadLine();         }          /// <summary>         /// 显示数组信息         /// </summary>         /// <typeparam name="T"></typeparam>         /// <param name="os"></param>         public static void ShowMessage<T>(T[] array)         {              foreach(T member in array)             {                 Console.WriteLine(member.ToString());             }              Console.WriteLine("-----------------------");             Console.WriteLine();         }     }

Filter the returned member types

You can call the GetMembers, GetFields, GetMethods, GetProperties or GetEvenents method of Type to query the members of a type. When calling any of the above methods, you can pass an instance of the System.Reflection.BindingFlags enumeration type. The purpose of using this enumeration type is to filter the members returned by these methods.

Note: Among all methods that return a member collection, there is an overloaded version that does not obtain any actual parameters. If the BindingFlags actual parameter is not passed, all these methods return public members, and the default setting is BindingFlags.Public|BindingFlags.Instance|BindingFlags.Static. (If Public or NonPublic is specified, Instance must be specified at the same time, otherwise no member will be returned).

The above is the detailed content of What are assembly loading and reflection mechanisms in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete