Table of Contents
Use generics to shield type differences
1. Generic class
2. Generic interface
3. Generic methods
4. Generic wildcards
5. Generic upper and lower bounds
Home Java javaTutorial What impact does the type shielding feature of generics in Java have on code?

What impact does the type shielding feature of generics in Java have on code?

Apr 26, 2023 pm 01:34 PM
java

Use generics to shield type differences

In C language, there is a very useful template function, which can write a general version with parameterized types and let the compiler automatically generate Specific versions for different types. In the Java language, there is a similar function called generics. When writing classes and methods, specific types are generally used, and generics can be used to parameterize types, so that more general code can be written.

Many people believe that the two concepts of C template (template) and Java generic (generic) are equivalent, but in fact the implementation mechanisms are completely different. C template is a set of macro instructions, and the compiler will create a copy of the template code for each type; the implementation of Java generics is based on the concept of "type erasure", which is essentially a syntactic sugar for type restrictions.

1. Generic class

Take the support class as an example to define the general support class of generics:

/** 通用支撑类 */@Getter@Setter@ToStringpublic class GenericHolder<T> {    /** 通用取值 */
    private T value;    /** 构造函数 */
    public GenericHolder() {}    /** 构造函数 */
    public GenericHolder(T value) {        this.value = value;
    }
}
Copy after login

2. Generic interface

Definition Generic data provider interface:

/** 数据提供者接口 */public interface DataProvider<T> {    /** 获取数据函数 */
    public T getData();
}
Copy after login

3. Generic methods

Define generic shallow copy functions:

/** 浅拷贝函数 */public static <T> T shallowCopy(Object source, Class<T> clazz) throws BeansException {    // 判断源对象
    if (Objects.isNull(source)) {        return null;
    }    // 新建目标对象
    T target;    try {
        target = clazz.newInstance();
    } catch (Exception e) {        throw new BeansException("新建类实例异常", e);
    }    // 拷贝对象属性
    BeanUtils.copyProperties(source, target);    // 返回目标对象
    return target;
}
Copy after login

4. Generic wildcards

Generic wildcards generally use "?" instead of specific type arguments. You can regard "?" as the parent class of all types. When the specific type is uncertain, you can use the generic wildcard "?"; when you do not need to use the specific functions of the type and only use the functions in the Object class, you can use the generic wildcard "?".

/** 打印取值函数 */public static void printValue(GenericHolder<?> holder) {
    System.out.println(holder.getValue());
}/** 主函数 */public static void main(String[] args) {
    printValue(new GenericHolder<>(12345));
    printValue(new GenericHolder<>("abcde"));
}
Copy after login

In the Java specification, it is not recommended to use the generic wildcard "?". The above function can be changed to:

/** 打印取值函数 */public static <T> void printValue(GenericHolder<T> holder) {
    System.out.println(holder.getValue());
}
Copy after login

5. Generic upper and lower bounds

When using generics When type, we can also set upper and lower bounds for the passed in generic type actual parameters. For example, type actual parameters are only allowed to pass in a certain type of parent class or a certain type of subclass. The declaration of the upper and lower bounds of a generic type must be placed together with the declaration of the generic type.

Upper bound wildcard (extends):

The upper bound wildcard is "extends", which can accept its specified type or its subclass as a general parameter. There is also a special form that specifies that it must not only be a subclass of the specified type, but also implement certain interfaces. For example: List indicates that this is a List of a specific subclass of A, and the saved object must be A or a subclass of A. For the List list, you cannot add A or a subclass object of A, but can only get the object of A.

Lower bound wildcard (super):

The lower bound wildcard is "super", which can accept its specified type or its parent class as a general parameter. For example: List indicates that this is a List of a specific parent class of A, and the saved object must be A or a superclass of A. For List list, you can add A or a subclass object of A, but you can only get the object of Object.

PECS (Producer Extends Consumer Super) principle:
When providing data as a producer (reading out), it is suitable to use upper bound wildcards (extends);
As a consumer consuming data (reading in) When writing), it is appropriate to use the lower bound wildcard (super).

In daily coding, the upper bound wildcard (extends) is more commonly used, which is used to limit the parent class of a generic type. The example code is as follows:

/** 数字支撑类 */@Getter@Setter@ToStringpublic class NumberHolder<T extends Number> {    /** 通用取值 */
    private T value;    /** 构造函数 */
    public NumberHolder() {}    /** 构造函数 */
    public NumberHolder(T value) {        this.value = value;
    }
}/** 打印取值函数 */public static <T extends Number> void printValue(GenericHolder<T> holder) {
    System.out.println(holder.getValue());
}
Copy after login

The above is the detailed content of What impact does the type shielding feature of generics in Java have on code?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1677
14
PHP Tutorial
1279
29
C# Tutorial
1257
24
PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and Functionality PHP vs. Python: Core Features and Functionality Apr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP's Impact: Web Development and Beyond PHP's Impact: Web Development and Beyond Apr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP: The Foundation of Many Websites PHP: The Foundation of Many Websites Apr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

PHP vs. Python: Use Cases and Applications PHP vs. Python: Use Cases and Applications Apr 17, 2025 am 12:23 AM

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

Composer Expertise: What Makes Someone Skilled Composer Expertise: What Makes Someone Skilled Apr 11, 2025 pm 12:41 PM

To become proficient when using Composer, you need to master the following skills: 1. Proficient in using composer.json and composer.lock files, 2. Understand how Composer works, 3. Master Composer's command line tools, 4. Understand basic and advanced usage, 5. Familiar with common errors and debugging techniques, 6. Optimize usage and follow best practices.

Composer: Aiding PHP Development Through AI Composer: Aiding PHP Development Through AI Apr 29, 2025 am 12:27 AM

AI can help optimize the use of Composer. Specific methods include: 1. Dependency management optimization: AI analyzes dependencies, recommends the best version combination, and reduces conflicts. 2. Automated code generation: AI generates composer.json files that conform to best practices. 3. Improve code quality: AI detects potential problems, provides optimization suggestions, and improves code quality. These methods are implemented through machine learning and natural language processing technologies to help developers improve efficiency and code quality.

See all articles