Simple to use generics - Java foundation

0. Introduction

  • Inside the Java generics use in the actual development of many learned students must know C ++ C ++ templates and generics in Java, to some extent, and it is still quite like.
  • I believe people who write Java and large have used the List implementation class ArrayList. Before Java without generics, its interior is an Object array implementation. This also leads to a problem, every time there's an element used when needed downcast, and obviously, if it is Object, then, means that we can throw any object inside. Automatic transition into the Object, so that when in use it is easy to go wrong, I do not know what kept inside Yes. Such as:
    ArrayList list = new ArrayList();
    list.add("string1");
    list.add("string2");
    String str = (String) list.get(0);
    list.add(new File("test.txt"));
    复制代码
  • However, generic easy to use, we often use the generic List, but if we want to write a generic class is not so easy.

1. The most simple generic

package io.ilss.advanced.generic;

/**
 * className MyObject
 * description MyObject
 *
 * @author feng
 * @version 1.0
 * @date 2019-01-24 18:32
 */
public class MyObject<T> extends BaseData {
    private T valueOne;
    private T valueTwo;

    public MyObject(T valueOne, T valueTwo) {
        this.valueOne = valueOne;
        this.valueTwo = valueTwo;
    }

    public T getValueOne() {
        return valueOne;
    }

    public void setValueOne(T valueOne) {
        this.valueOne = valueOne;
    }

    public T getValueTwo() {
        return valueTwo;
    }

    public void setValueTwo(T valueTwo) {
        this.valueTwo = valueTwo;
    }

    public static void main(String[] args) {
        MyObject<String> object = new MyObject<>("String one!", "String two");
        System.out.println("value one " + object.valueOne + " value two " + object.valueTwo);
    }
}
复制代码
  • MyObject incorporated in a variable T type, with angle brackets <>enclose, on the back of the class name. As! When defining a plurality of types may be variable, in <>a comma-separated e.g. public class MyObject<T, U>{…}, directly in the class definition of the type of the variable can be regarded as a class name to use if you are using type.

2. Use a generic interface to make a return to class

  • I believe writing Java programmers have written Web interface that we use to encapsulate a generic class unified response ResponseMsg returned.
package io.ilss.advanced.generic;

/**
 * className ResponseMsg
 * description ResponseMsg
 *
 * @author feng
 * @version 1.0
 * @date 2019-01-24 18:47
 */
public class ResponseMsg<T extends BaseData> {
    public static int SUCCESS_CODE = 1;
    public static int ERROR_CODE = 0;
    public static int OTHER_CODE = -1;
    private int code;
    private String msg;
    private T data;

    public static <U extends BaseData> ResponseMsg sendSuccess(U data) {
        ResponseMsg<U> responseMsg = new ResponseMsg<>();
        responseMsg.code = SUCCESS_CODE;
        responseMsg.data = data;
        responseMsg.msg = "Remote Call Success!";
        return responseMsg;
    }

    public static <U extends BaseData> ResponseMsg sendError(U data, String msg) {
        ResponseMsg<U> responseMsg = new ResponseMsg<>();
        responseMsg.code = ERROR_CODE;
        responseMsg.data = data;
        responseMsg.msg = "Remote Call Error";
        return responseMsg;
    }
    public static <U extends BaseData> ResponseMsg sendOther(U data, String msg) {
        ResponseMsg<U> responseMsg = new ResponseMsg<>();
        responseMsg.code = OTHER_CODE;
        responseMsg.data = data;
        responseMsg.msg = msg;
        return responseMsg;
    }

    public static void main(String[] args) {
        System.out.println(ResponseMsg.<MyObject>sendSuccess(new MyObject<String>("asdf","asfd")));
    }

    @Override
    public String toString() {
        return "ResponseMsg{" +
                "code=" + code +
                ", msg='" + msg + '\'' +
                ", data=" + data +
                '}';
    }
}
复制代码
  • The focus is on the top of <U>me with a static method encapsulates the ResponseMsgbuilding, only need to provide a static method call to let people pass in a class, you can not write Getter Setter method, or directly into private methods.
  • If a generic method of use, only when the timing required for the return type of the front can be used together. When invoked directly in front of the method call with <>the incoming class you want to use. As indicated above, the method may be passed directly to their generic generic class definition.
  • Furthermore it can also extendsdefine you are certain subclass or implements an interface. If there are a plurality of interfaces may be connected to & such <T extends Comparable & Serializable>, if there may be a plurality of generic<T extends OneObject, U extends TwoObject>

3. Note

  • Generics can not directly newrequire external incoming. Such as:
     T data = new T();     //这是不被允许的,不能实例化对象
     T[] arr = new T[10];  //这也是不被允许的  不能构造泛型数组
    复制代码

about me

  • Coordinate Hangzhou, ordinary undergraduate reading, computer science and technical expertise, graduation 20 years, is currently in the practice stage.
  • Mainly doing Java development, will write about Golang, Shell. Micro services, Big Data interested, ready to do in this direction.
  • Is currently in the rookie stage, you chiefs light spray, crazy brother is learning.
  • I welcome you and exchange duck! ! !

Guess you like

Origin juejin.im/post/5d137c79e51d45775c73dd20