What are the principles behind Java generics?

Keywords: Java jvm Attribute

Yunqi information:[ Click to see more industry information]
Here you can find the first-hand cloud information of different industries. What are you waiting for? Come on!

The main content of this section is the application of generics in java. Through this section, you can better understand generics and what is the concept of generics type erasure often mentioned in interviews. Let's look at it with these questions today:
Take a simple example:

It can be seen that the error has been reported in the code writing stage, and the data of type int cannot be added to the collection of type string.
Can we add multiple types of data to the list set? The answer is yes. In fact, we can treat the list set as a common class. Then there is the following code:

It can be seen from here that you can add data to a collection without defining generics, so generics are just a type specification, which is a limitation in the code writing phase.
Let's take an example to show what kind of data is behind generics

public class BaseBean<T> {
    T value;

    public T getValue() {
        return value;
    }

    public void setValue(T value) {
        this.value = value;
    }
}

The above defines a generic class, and then we get the data type returned by the property and getValue method through reflection:

It can be seen from the log that the attribute obtained through reflection is of type object, and the returned attribute in the method is of type string. Therefore, we can think that in the getValue method, we have actually made a strong conversion action to convert the value of type object into type string.

Yes, that's right, because generics are only used to constrain our code specification, but there is no generics for virtual machine after class is compiled and handed over to virtual machine. All generics are object type in its view, so generics erasure is for virtual machine.
Let's look at a generic structure:




public class BaseBean<T> {
    public String errMsg;
    public T data;
    public int status;
}

Generics on abstract classes or interfaces

//Abstract class generics
public abstract class BaseAdapter<T> {
    List<T> DATAS;}//Interface generic public interface factory < T >{
    T create();
}
//Method generics
public static <T> T getData() {
    return null;
}

Multivariate generics

public interface Base<K, V> {
    void setKey(K k);

    V getValue();}

Generic second level abstract class or interface

public interface BaseCommon<K extends Common1, V> extends Base<K, V> {
}

//Or abstract class
public abstract class BaseCommon<K extends Common1, V> 
implements Base<K, V> {
}

Abstract contains Abstract

public interface Base<K, V> {
   //    void setKey(K k);////    V getValue();
   void addNode(Map<K, V> map);

   Map<K, V> getNode(int index);}public abstract class BaseCommon<K, V> implements Base<K, V> {
   //Multiple generics
   LinkedList<Map<K, V>> DATAS = new LinkedList<>();

   @Override
   public void addNode(Map<K, V> map) {
       DATAS.addLast(map);
   }

   @Override
   public Map<K, V> getNode(int index) {
       return DATAS.get(index);
   }
}

wildcard

The difference between a wildcard and a wildcard is that when you don't know the generic type, you can define it with a wildcard. Here's an example to see the use:

//A common class is defined
public class BaseBean<T> {
    T value;

    public T getValue() {
        return value;
    }

    public void setValue(T value) {
        this.value = value;
    }
}

//Used to define generic
public class Common1 extends Common {
}

public static void main(String\[\] args) {
    BaseBean<Common> commonBaseBean = new BaseBean<>();
    //There's no problem with wildcard definitions
    BaseBean<?> common1BaseBean = commonBaseBean;
    try {
        //Guess the parameter of setValue is Object type through reflection
        Method setValue = common1BaseBean.getClass().getDeclaredMethod("setValue", Object.class);
        setValue.invoke(common1BaseBean, "123");
        Object value = common1BaseBean.getValue();
        System.out.println("result:" + value);
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    }
}

If the generic defined above is wildcard, it can be equivalent. Because the parameter of setValue at this time is Object type, the generic defined above can be directly assigned to the BaseBean of wildcard.
In addition, WeChat official account: Internet architects reply in the background: 2T, can get the architect video tutorial, all dry cargo.
Wildcards cannot be defined on a class, an interface, or a method, but only on the parameters of a method

public void setClass(Class<?> class){
    //todo
}

,,<? extends>,<? super>
Represent upper limit generics, represent lower limit generics
To demonstrate the role of these two wildcards, a class is added:

public void add(Class<? super Common> clazz) {}

It can be seen that when Common1.class is passed in, it is illegal. Because the bytecode object of the Common parent class needs to be passed in the add method, and Common1 is inherited from Common, so it is directly illegal.

In the actual development, it's ok to know when to define what type of generics. In the mvp case, generics are widely used. You can find the feeling of generics according to the actual project, but you need to understand who type erasure is for when interviewing. WeChat official account: Internet architects, get more structured technology dry cargo.

Type Erasure

In fact, at the beginning of the article, it has been illustrated by examples that the definition of generics is bypassed by reflection, and that the generics defined in the class are finally executed by the jvm as objects.
When all generics are executed in the jvm, they exist as Object objects. Adding generics is only for a kind of code specification, avoiding another strong transition in the development process.
Generic information only exists in the code compilation stage. Before entering the JVM, the generic information will be erased. The technical term is type erasure.

[yunqi online class] product technology experts share every day!
Course address: https://yqh.aliyun.com/zhibo

Join the community immediately, face to face with experts, and keep abreast of the latest news of the course!
[yunqi online classroom community] https://c.tb.cn/F3.Z8gvnK

Original release time: May 27, 2020
Author: a scene of
This article comes from:“ Internet architect WeChat official account ”, you can pay attention to“ Internet architect"

Posted by ravi.kinjarapu on Wed, 27 May 2020 01:53:39 -0700