Explanation of java Basic Development Generic Class

  • 2021-11-24 01:40:58
  • OfStack

Catalog Preface Generic Concept Generic Class Conclusion

Preface

In software development, many execution processes are very similar. Many people use copy and paste to complete the function. Although the compiler will not report errors, it will use wavy lines to give prompts, which brings great hidden dangers to future maintenance. In this case, developers usually extract common methods, common classes or use inheritance according to the required members, which improves the reuse of code. However, in some special cases (for example, objects will be used in the execution process, and these objects operate the same, but the specific modules are different), at this time, generics can only be used to complete code reuse.

Generic concept

Generics parameterize a type from its original concrete type, similar to variable parameters in a method, where the type is also defined as a parameter. This parameter type can be used in classes, interfaces and methods, which are called generic classes, generic interfaces and generic methods respectively. In actual programming, generics allow you to define type-safe data structures (type-safe) without using actual data types (extensible). This can significantly improve performance and get higher quality code (high performance), because you can reuse data processing algorithms without copying type-specific code (reusable)

Generic class

In the ArrayList class, ArrayList can put various objects, such as String, Integer, pojo, etc., and can complete their add (), get (), etc. When declaring, it is used when constructing an array list < > To explain what kind of things are put in this container, such as ArrayList < String > Represents the String collection, and ArrayList is a generic class, in which the type of storing object is defined by parameters, and this class is a generic class.

Because of the different types of the 1 set of operations, we have to define different functions, resulting in a lot of basically identical code. Programmers have become accustomed to using generic classes in collections. In fact, generics are more widely used in the processing of business logic. A generic class defines a set of operations in which the same process is completed.

"Example": In SSM mode, multiple modules controller need to complete the functions of paging information acquisition, fuzzy query according to name, query according to administrative division code and other conditions. The services objects that need to be accessed in controller of each module are different, so a generic class can be designed to write corresponding codes to avoid a large number of copied codes.


public class TemplateController<T extends IBaseService,E> {
    private Logger logger = LoggerFactory.getLogger(getClass());
    private T t;
    // Pass in when calling T Object of 
    public TemplateController(T obj){
        t=obj;
    }

    public R getList(Map<String, Object> params){
        try {
            String pageSize = params.get("pagesize").toString();
            String currPage = params.get("currpage").toString();
            String cName = params.get("CName").toString();
            String regionCode = params.get("regionCode").toString();
            long size = Long.parseLong(pageSize);
            long currPageNo = Long.parseLong(currPage);
            Page<E> page=new Page<>(currPageNo,size);

            // Code truncation when querying provinces and cities 
            String  code = RegionCode.GetRegionCode(regionCode);
            PageUtils data = t.getList(page,cName,code);
            return R.ok().put("data", data);
        } catch (Exception e) {
            logger.debug(" Error in incoming data "+e.getStackTrace());
            return R.error(" Error in incoming data "+e.getMessage());
        }
    }
}

TemplateController < T extends IBaseService,E > Is a generic class,

Two type parameters are defined, which are < T,E > Where T is a bounded type, defined as a class that implements the IBaseService interface.
IBaseService defines the getList method, which is called when the data extraction operation is completed.

The IBaseService code is as follows:


public interface IBaseService<T> {
    // Take paging records 
    PageUtils getList(Page<T> page, String cName, String regionCode); 
}

The use of generics, ArtBankController inherits the generic class, will inject the object into the generic class, the execution of the code is very simple,


@RequestMapping("bank")
public class ArtBankController extends TemplateController<ArtBankService,ArtBankEntity> {

    @Autowired
    private ArtBankService jobArtBankService;

    public ArtBankController(ArtBankService jobArtBankService) {
        super(jobArtBankService);
    }

    // The execution code is simple, just calling the parent class's getList Method is sufficient 
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params){
        return this.getList(params);
    }
 }

Many modules in the business need to be paged. When querying by name and administrative division, the code reuse is realized

Conclusion

You are already familiar with using generics in collection classes (map, list, set), but not much for custom generic classes in your own business. It is not difficult to find the usage scenarios of generic classes as long as we focus on the two themes of extensibility and maintainability and are good at summarizing them in development

The above is the java basic development generic class details, more about the java basic generic class information please pay attention to other related articles on this site!


Related articles: