Let's analyze Java generics and generic wildcards together
This article brings you relevant knowledge about java, which mainly introduces issues related to generics and generic wildcards, because the support of generics is compiler support, byte Generic information has been erased when the code is loaded into the virtual machine, so generics do not support some runtime features. Let's take a look at them together. I hope it will be helpful to everyone.
Recommended study: "java video tutorial"
Generics are not a runtime feature
We still have it here What I’m talking about is Open JDK
Because generic support is supported by the compiler, the generic information has been erased when the bytecode is loaded into the virtual machine, so generics do not support some runtime features. So be aware that some writing methods will not compile, such as new.
As follows, the class Plate
new Plate(...) new Plate<T>(...) class Plate<T> { T item; public Plate(T t) { new T();//是错误的,因为T是一个不被虚拟机所识别的类型,最终会被编译器擦除转为Object类给到虚拟机 item = t; } public void set(T t) { item = t; } public T get() { return item; } }
The generic T cannot be new, because T is a type that is not recognized by the virtual machine.
Generic wildcard
There are three forms of generic variable expression using wildcard characters, which are:
- ## extends A>: C extends A> c, the element types in c are all A or subclasses of A ## super B>:C super B> c, in c The element type is B or the parent class of B
- ##>: C> c, the element type in c is uncertain
- Let’s take a look at what it specifically means and how to use it~
public interface RequestBodyAdvice {
/**
* Invoked first to determine if this interceptor applies.
* @param methodParameter the method parameter
* @param targetType the target type, not necessarily the same as the method
* parameter type, e.g. for {@code HttpEntity<String>}.
* @param converterType the selected converter type
* @return whether this interceptor should be invoked or not
*/
boolean supports(MethodParameter methodParameter, Type targetType,
Class<? extends HttpMessageConverter<?>> converterType);
...
}
@Override public boolean supports(MethodParameter methodParameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) { return (AbstractJackson2HttpMessageConverter.class.isAssignableFrom(converterType) && methodParameter.getParameterAnnotation(JsonView.class) != null); }
@Override public HttpInputMessage beforeBodyRead(HttpInputMessage request, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) throws IOException { for (RequestBodyAdvice advice : getMatchingAdvice(parameter, RequestBodyAdvice.class)) { if (advice.supports(parameter, targetType, converterType)) { request = advice.beforeBodyRead(request, parameter, targetType, converterType); } } return request; }
The expression using the previous wildcard can no longer set the generic field. In fact, it means that the upper bound wildcard is no longer set. Wildcards cannot change the set generic type. Let's take a look at this demo.
@Test void genericTest() { Plate<Apple> p = new Plate<Apple>(new Apple()); p.set(new Apple());//可以set Apple apple = p.get(); Plate<? extends Fruit> q = new Plate<Apple>(new Apple()); Fruit fruit = q.get(); q.set(new Fruit());//将编译错误 }
We easily fall into a trap in understanding, thinking that we can only set Fruit or the base class of Fruit. In fact, only Fruit and Fruit subclasses can be set in. Let's write a unit test to see.
@Test void genericSuperTest() { Plate<? super Fruit> p = new Plate<Fruit>(new Fruit()); p.set(new Apple()); //ok,存取的时候可以存任意可以转为T的类或T p.set(new Object()); //not ok,无法 set Object Object object = p.get();//ok Fruit object = p.get();//not ok,super Fruit不是Fruit的子类 }
Now, let’s look at a practical example.
SettableListenableFuture是spring 并发框架的一个类,继承自Future
在spring-kafka包里使用了SettableListenableFuture来设置异步回调的结果,kafka客户端调用 doSend发送消息到kafka队列之后,我们可以异步的判断是否发送成功。
public class SettableListenableFuture<T> implements ListenableFuture<T> { ... @Override public void addCallback(ListenableFutureCallback<? super T> callback) { this.settableTask.addCallback(callback); } @Override public void addCallback(SuccessCallback<? super T> successCallback, FailureCallback failureCallback) { this.settableTask.addCallback(successCallback, failureCallback); } ...
SettableListenableFuture有重载的addCallback函数,支持添加ListenableFutureCallback super T> callback和SuccessCallback super T> successCallback;当调用的异步方法成功结束的时候使用notifySuccess来触发onSuccess的执行,这个时候将实际异步执行的结果变成参数给callback调用。
private void notifySuccess(SuccessCallback<? super T> callback) { try { callback.onSuccess((T) this.result); } catch (Throwable ex) { // Ignore } }
SuccessCallback是一个函数式接口,从设计模式的角度来看是一个消费者,消费
public interface SuccessCallback<T> { /** * Called when the {@link ListenableFuture} completes with success. * <p>Note that Exceptions raised by this method are ignored. * @param result the result */ void onSuccess(@Nullable T result); }
为什么要用notifySuccess(SuccessCallback super T> callback)呢?
这是因为super能支持的范围更多,虽然实际产生了某一个具体类型的结果,比如kafka的send函数产生的结果类型为SendResult,其他的客户端可能使用其他的Result类型,但是不管是什么类型,我们在使用Spring的时候,可以对异步的结果统一使用Object来处理。
比如下面的这段代码,虽然是针对kafka客户端的。但对于其他的使用了Spring SettableListenableFuture的客户端,我们也可以在addCallback函数里使用Object来统一处理异常。
@SneakyThrows public int kafkaSendAndCallback(IMessage message) { String msg = new ObjectMapper().writeValueAsString(message); log.debug("msg is {}. ", msg); ListenableFuture send = kafkaTemplate.send("test", msg); addCallback(message, send); return 0; } private void addCallback(IMessage msg, ListenableFuture<SendResult<String, String>> listenableFuture) { listenableFuture.addCallback( new SuccessCallback<Object>() { @Override public void onSuccess(Object o) { log.info("success send object = " + msg.getContentType() + msg.getId()); } }, new FailureCallback() { @Override public void onFailure(Throwable throwable) { log.error("{}发送到kafka异常", msg.getContentType() + msg.getId(), throwable.getCause()); } }); } }
声明某个条件的任意类型?
比如 Collection
@Override public boolean removeAll(Collection<?> collection) { return delegate().removeAll(collection); }
Collection的removeAll函数移除原集合中的一些元素,因为最终使用equals函数比较要移除的元素是否在集合内,所以这个元素的类型并不在意。
我们再看一个例子,LoggerFactory
public class LoggerFactory { public static Logger getLogger(Class<?> clazz) { return new Logger(clazz.getName()); } }
LoggerFactory可以为任意Class根据它的名字生成一个实例。
总结:设计模式PECS
PECS是producer extends consumer super的缩写。
也是对我们上面的分析的一个总结
意思是extends用于生产者模式,而super用于消费者模式。
消费者模式:比如上面的callback结果是为了消费;这些结果被消费处理。
生产者模式:比如那些Converter,我们要处理特定格式的http请求,需要生产不同的转换器Converter。
推荐学习:《java视频教程》
The above is the detailed content of Let's analyze Java generics and generic wildcards together. 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











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

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 and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

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 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.

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

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 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.
