JAVA: Generic role

1, the generic concept      

     java generics, a java  SE 1.5 new features, the generic nature of the parameterized type , that is to say the operation of the data type is specified as a parameter. This parameter type may be used in the creation of classes, interfaces and methods, we are called generic class [], [] generic interfaces, generic method []. 

       Generic (Generic type or generics) is a language for the Java type system extensions , to support the creation of a class can be parameterized by type. Can be considered as specified by the type parameter parameterized types using a type of placeholder as the formal parameter transfer method is the same runtime placeholder values.

        Motivation can be seen in the collections of the generic framework (Collection framework) in. For example, Map class allows you to add objects of any class to a Map, even though the most common situation in a given map (map) objects of a particular type (such as String) are stored.
Since Map.get type () is defined to return Object, it is generally necessary to result Map.get () is cast into a desired, as shown in the following code:
 

//未使用泛型
Map map1 = new HashMap();
map1.put("key", "values");
String str1 = (String) map1.get("key");

        The get () results cast a String, the program can be compiled successfully, and hope the result is really a String. However, other types of data can be stored in the map mediator, so the above code will throw an exception: ClassCastException.
Ideally, you might come to a view that is a map1 Map, it will be mapped to String key String value. This allows you to eliminate casts code while gaining an additional layer of type checking, the checking layer may prevent some people the wrong type of key or value stored in the collection. This is the generic work done.

//使用泛型
Map<String,String> map2 = new HashMap();
map2.put("key", "values");
String str2 = map2.get("key");

2, the role of generics

    Java language, the introduction of generic exercise in a larger enhancements. Not only the language, the type system and compiler has made significant changes to support generics, and libraries have also been major renovations, so many important classes, such as collections framework, it has become a generic of. Role is as follows:

1, type-safe. 

    The main objective is to improve the generic type-safe Java programs. Strong type checking at compile time; by knowing the use of the generic type restrictions defined variables, the compiler can verify the type assumed a much higher degree on. Without generics, these assumptions will exist only in the mind of the programmer (or, if lucky, also in the code comments).

2, the elimination of mandatory conversion. 

    A side benefit of generics is to eliminate many casts in the source code. This makes the code more readable, and reduces the opportunities for error.

3, the potential performance gains. 

    Generic likely to bring greater optimization. In the initial implementation of the generic, compiler casts (not generic, then the programmer specifies the cast) into the bytecode generated. But more types of information available to the compiler this fact, could bring order to optimize future versions of the JVM. Due to the generics implementation, support for generics (almost) does not require the JVM or class file changes. All work is done in the compiler, the compiler generates code written when there is no similar generic (and cast), but can also ensure that the type of security only.

     Java language advantages of the introduction of generics is safe and simple. The benefits of generics are checked at compile time type safety, and all the cast are automatic and implicit, improve code reuse.

4, better code reusability, such as generic algorithms to achieve

    In the framework of design time, BaseDao <T>, BaseService <T>, BaseDaoImpl <T>, BaseServiceImpl <T>; through inheritance, all the realization of the abstract public methods to avoid writing the same code every time.

3, generic usage scenarios

1) collection

2) generic class

    Packaging category return parameters, the following code.

3) generic interface

4) generic method

 

import com.fasterxml.jackson.annotation.JsonView;
import com.myfutech.common.util.enums.ResponseCode;
import com.myfutech.common.util.vo.BaseView;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

@ApiModel(value = "Responses", description = "响应信息")
public class Responses<T> {

    public static <T> Responses<T> success(){
        return new Responses<>(ResponseCode.SUCCESS_CODE, "", null);
    }

    public static <T> Responses<T> success(T result){
        return new Responses<>(ResponseCode.SUCCESS_CODE, "", result);
    }

    public static <T> Responses<T> success(String msg, T result){
        return new Responses<>(ResponseCode.SUCCESS_CODE, msg, result);
    }

    public static <T> Responses<T> error(String msg){
        return new Responses<>(ResponseCode.ERROR_CODE, msg, null);
    }

    public static <T> Responses<T> error(ResponseCode code){
        return new Responses<>(code, code.getDefaultMsg(), null);
    }

    public static <T> Responses<T> error(ResponseCode code, String msg){
        return new Responses<>(code, msg, null);
    }

    @JsonView(BaseView.class)
    @ApiModelProperty("响应编码")
    private String code;
    @JsonView(BaseView.class)
    @ApiModelProperty("响应消息")
    private String msg;
    @JsonView(BaseView.class)
    @ApiModelProperty("响应体")
    private T result;

    public Responses() {
    }

    private Responses(ResponseCode code, String msg, T result) {
        this.code = code.getCode();
        this.msg = msg;
        this.result = result;
    }

    public String getCode() {
        return code;
    }

    public boolean notSuccess() {
        return !ResponseCode.SUCCESS_CODE.getCode().equals(code);
    }

    public String getMsg() {
        return msg;
    }

    public T getResult() {
        return result;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public void setResult(T result) {
        this.result = result;
    }
}

 

4, the use of generic rules and restrictions

    1, only a generic type parameter class types (including custom class), may not be a simple type.

    2, the same may correspond to a plurality of generic versions (because the parameter type is uncertain), different versions of the generic class instance are not compatible.

    3, the generic type parameter can have multiple.

    4, the generic type parameter extends statement can be used, for example <T extends superclass>. Become accustomed to the "bounded type."

    5, the generic parameter type may also be wildcard type. <?> E.g. Class classType = Class.forName (Java.lang.String);
    

 

Guess you like

Origin blog.csdn.net/jiahao1186/article/details/91411606