Type erasure in. NET generics and Java generics

Source: Internet
Author: User

Open Type and closed type. NET regard the type with type parameters as a new type. CLR creates an internal type object for these types, which applies to classes, structures, interfaces, and delegation. However, when a type with a type parameter becomes an open type, CLR does not allow open type instantiation (just like interface instantiation is not allowed ). When the generic type is referenced in the code, you can specify a set of generic type parameters in the code. If the actual data type is input, this type becomes a closed type, and CLR allows instantiation of the closed type. However, it is also possible that the code references the generic type, but the generic type parameter is not specified. This creates a new open type in CLR, which cannot be instantiated, let's look at an example. Internal sealed class DictionaryStringKey <TValue>: Dictionary <String, TValue >{} static void Main (string [] args) {Object o = null; // Dictionary <,> there are two open Type parameters: Type t = typeof (Dictionary <,>); // instance creation failure o = CreateInstance (t); Console. writeLine (); // DictionaryStringKey <> there is a development type t = typeof (DictionaryStringKey <>) of the type parameter ); // creating an instance of this type will also fail o = CreateInstance (t); Console. writeLine (); // DictionaryString Key <Guid> is a closed type t = typeof (DictionaryStringKey <Guid>); // o = CreateInstance (t) created successfully; // name of the output type Console. writeLine ("Object type =" + o. getType ();} private static Object CreateInstance (Type t) {Object o = null; try {// use the default constructor to create this Type of instance o = Activator. createInstance (t); Console. write ("Created instance of {0}", t. toString ();} catch (ArgumentException e) {Console. writeLine (e. message);} return o;} Running result: When Activator. CreateInstance creates an instance, it will prompt you that this type contains generic parameters. In the output, you can see that the type name is followed by Reverse quotation marks (') and a number. This number is the number of type parameters. For example, the generic Dictionary class is 2 because it requires two type parameters to indicate TKey and TValue. The DictionaryStringKey class has only one because it only needs to specify one TValue type .. In type. NET, in addition to the instance constructor, CLR also supports the Type constructor (also known as static enough, and the class is enough in it or the type initiator ). The Type constructor can be applied to an interface (not supported in c #), a reference type (class) and a value type (struct). It is the same as an instance of the Instance constructor initialization type, the Type constructor is used to initialize some states of the type. If there is a Type constructor, there may be only one and there is no parameter. Refer to the previous article. http://cnn237111.blog.51cto.com/2359144/576533 The CLR ensures that the type initiator runs only once and is thread-safe. Therefore, the type initiator is applicable to the initialization of the singleton object in singleton mode. Static fields in the type can be considered as part of the type, while non-static fields in the type can be considered as part of the Instance Object. When the JIT compiler converts the IL language to the CPU at a certain cost, it will encounter many types (such as custom classes). In order to correctly load the Assembly containing these types, CLR, it extracts type information through the Assembly metadata, and then creates these types of data structures. These data structures are stored as objects in the heap. All objects in the heap have two members, type object pointers and synchronized block indexes. Static fields defined in the data type are also included in the data structure object. All instance objects of the class share the same static field of the type object. For example, the Manager in the box is a type object, and the static field exists in the type object. The instance object is represented by an elliptical box pointing to a type object. For. NET generic types, each closed type has its own static field. In other words, static fields in List <> and List <String> are independent of each other. Similarly, if a generic type defines a static constructor, these constructor also runs according to their own closed type. That is to say, List <DateTime> and List <String> have their own static constructors. Static void Main (string [] args) {bool issame = typeof (List <DateTime>) = typeof (List <string>); Console. writeLine (issame); object o = Activator. createInstance (typeof (List <DateTime>); Console. writeLine (o. getType (); o = Activator. createInstance (typeof (List <string>); Console. writeLine (o. getType ();} run the following results: Type erasure in Java generics is often heard that Java generics are pseudo generics, because during compilation or running, java JIT erases the type. That is to say, the JVM cannot really recognize the generic type. Therefore, the generic type is converted to the original type before the actual operation. Therefore, all generic types share the same type object. For example, if the List <Integer> type is erased and converted to a non-generic List, this List can store any type of data. Therefore, the type cannot be obtained when Java is running. Of course, reflection may be known, but it is not always possible to obtain the type. Therefore, in Java code, different generic types actually come from the same type. For example, the following code: public static void main (String [] args) throws Exception {List <Integer> li = new ArrayList <Integer> (); list <Float> lf = new ArrayList <Float> (); boolean issame = li. getClass () = lf. getClass (); System. out. println (issame); // true Object o = li. getClass (). newInstance (); System. out. println (o. getClass (). getName (); // java. util. arrayList o = lf. getClass (). newInstance (); System. out. println (o. getClass (). GetName (); // java. util. because of code erasure, ArrayList} shares all types of objects in the generic type, so static fields of the type are also shared. For example, the following code: public class AtestClass <E> {public static int I = 0; public AtestClass () {I ++ ;}---------------- public static void main (String [] args) throws Exception {AtestClass <Integer> ai = new AtestClass <Integer> (); AtestClass <Float> af = new AtestClass <Float> (); System. out. println (AtestClass. i);} The final running result is 2.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.