Understanding of Java generics (Class, Class<?>, Class<? extends T>, Class<? super T>)

What are generics?

Generics, or "parameterized types". When it comes to parameters, the most familiar thing is that there are formal parameters when defining a method, and then the actual parameters are passed when calling this method. So how to understand the parameterized type?
As the name implies, it is to parameterize the type from the original specific type, similar to the variable parameters in the method. At this time, the type is also defined as a parameter form (which can be called a type parameter), and then the specific type is passed in when using/calling type (type argument).

Uses of Generics

When we put an object into a collection, the collection will not remember the type of the object. When the object is taken out of the collection again, the compiled type of the object becomes Object type, but its runtime type is still its itself type.

Generic understanding (code level)

Let me first implement a very simple scenario. Now we have a scenario. We assume that class B inherits class A. Based on certain business requirements, we pass in a parameter of type Class in the constructor of class C.

Code implementation (problem code)

package test;

public class Test {
    
    
    public Test(Class<A> aClass){
    
    

    }


    public static void main(String[] args) {
    
    
        Test test1 = new Test(A.class);//编译正常
        Test test2 = new Test(B.class);//编译错误
    }
}


class A{
    
    

}


class B extends A{
    
    

}

Run and find that the code reports an error and finds a problem? Why is it that class B inherits from class A, but still reports an error?

Reason: Simply put, there is no constructor of this type.
The constructor Test(Class ) is undefined

How to solve this problem so that A and B can be realized at the same time?

Solved by generics (where:T is a type? for any wildcard):
There is a special way of expressing inheritance/implementation relationship in generics: (Let me introduce some of them below)

  1. Class means that it can be placed in any class to return an object
  2. Class indicates that only T class can be received
  3. Class<? extends T> indicates that only T class and T subclasses can be received
  4. Class<? super T> indicates that it can only receive T and its parent class

Code implementation (optimized code)

package test;

public class Test {
    
    
	//通过泛型Class<? extends A> aClass,标识接收对象为A与A的子类
    public Test(Class<? extends A> aClass){
    
    

    }


    public static void main(String[] args) {
    
    
        Test test1 = new Test(A.class);
        Test test2 = new Test(B.class);
    }
}


class A{
    
    

}


class B extends A{
    
    

}

Guess you like

Origin blog.csdn.net/Ghoul___/article/details/130060571