


What impact does the type shielding feature of generics in Java have on code?
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; } }
2. Generic interface
Definition Generic data provider interface:
/** 数据提供者接口 */public interface DataProvider<T> { /** 获取数据函数 */ public T getData(); }
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; }
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")); }
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()); }
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 extends A> 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 extends A> 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 super A> 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 super A> 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()); }
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics





Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.
