Java Generics invoking user class explanation
Dave Syer wrote the following class in a package org.springframework.security.oauth2.config.annotation.builders
.
public class ClientDetailsServiceBuilder<B extends ClientDetailsServiceBuilder<B>> extends
SecurityConfigurerAdapter<ClientDetailsService, B> implements SecurityBuilder<ClientDetailsService> {
}
I am having difficulty understanding this code. Can anyone explain the use of generics here and what Dave is trying to achieve here?
source to share
It is called a recursive type boundary. Here is B
defined in terms ClientDetailsServiceBuilder
. But since it is the type that is just being declared, B
it reappears to satisfy the type parameter.
A more general explanation that I found helpful: http://www.angelikalanger.com/GenericsFAQ/FAQSections/TypeParameters.html#FAQ106
Another good example for this pattern:
public interface Tree<T extends Tree<T>> {
List<T> getChildren();
}
This definition makes subtypes (implementations) Tree
automatically return the children of their type parameter, which must Tree
and may even be their actual type . If the return type was only List<Tree>
, callers expecting the subtype might need to do so.
source to share
By using class MyClass<T extends MyClass<T>>
, you can access any type of the subclass as a generic type.
This allows you to do things like this:
class MyClass<T extends MyClass<T>> {
private int value;
T withValue(int value) {
this.value = value;
return (T) this;
}
}
class MySubclass extends MyClass<MySubclass> {
private String name;
public MySubclass withName(String name) {
this.name = name;
return this;
}
}
MySubclass s = new MySubclass()
.withValue(5)
.withName("John Doe");
source to share