Type inference to general method and general class

Unable to understand general Java programming.

I have read a few lessons about this, but am still rather confused, especially when things get complicated.

Can someone explain what is happening in this example?

import java.util.Date;

public class Test1 {

    public static void main(String[] args) {
        P<Cls> p = new P<>();   //<1>   //I expect a ClassCastException here, but no. Why? //How does the type inference for class P<E> work? 
        System.out.println(p.name); //it prints
//      System.out.println(p.name.getClass());//but this line throws ClassCastException //why here? why not line <1>?

        test1(p);//it runs
//      test2(p);//throws ClassCastException//What is going on in method test1&test2? 
                //How does the type inference for generic methods work in this case?
        }


    public static<T> void test1(P<? extends T> k){
        System.out.println(k.name.getClass());
    }

    public static<T extends Cls> void test2(P<? extends T> k){
        System.out.println(k.name.getClass());
    }
}

class P<E>{
    E name = (E)new Date();//<2>
}

class Cls{}
+4
source share
1 answer
P<Cls> p = new P<>();

Remember that Java implements generics by erasing, which means that the constructor for Pdoes not really know what Eis at run time. Java generics are essential to help developers at compile time.

, new P<>() new Date(), - , E. E , P<E>. name - Object, Date. , , , name , , (Cls ), , .

  • p.name.getClass() ((Cls)p.name).getClass(), .
  • test2() , (extends Cls). , p.name.getClass() ((Cls)p.name).getClass().

:

  • System.out.println(p.name) System.out.println((Object)p.name), println - , Object.
  • test1(p.name) . T, p.name Object getClass() .

, , :

class P{
    Object name = new Date();
}

public static void main(String[] args) {
    P p = new P();   
    System.out.println(p.name);
    System.out.println(((Cls)p.name).getClass());

    test1(p);
    test2(p);
}


public static void test1(P k){
    System.out.println(k.name.getClass());
}

public static void test2(P k){
    System.out.println(((Cls)k.name).getClass());
}
+2

All Articles