Type conversion problems caused by Java generic type erasure

Source: Internet
Author: User

Preliminary conclusion: Generic type conversion is not reliable;

Source:

 Package Com.srie.testjava;  Public class Testclassdefine4<t> {    publicstaticvoid  main (string[] args) {        TestClassDefine4 New Testclassdefine4<string>();         = T4.badcast (1);        System.out.println (cast);    }    T Badcast (Integer i) {        return//  here is warning    }}

Anti-compilation:

 Package Com.srie.testjava; Import Java.io.PrintStream;  Public class Testclassdefine4<t>{  publicstaticvoid  main (string[] args)  {    new  TestClassDefine4 ();     = (String) t4.badcast (integer.valueof (1));    System.out.println (cast);  }  T Badcast (Integer i) {    return  i;  }}

Run Exception:

Exception in thread "main" Java.lang.ClassCastException:java.lang.Integer cannot is cast to java.lang.String    at Com.srie.testjava.TestClassDefine4.main (Testclassdefine4.java:7)

Type conversion problems caused by Java generic type erasure

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.