what does following Java line of code means
I found this class in magnolia CMS source which uses class definition I am not yet familiar with. Could anyone having knowledge about usage of the following code style explain to me what exactly this does?
In this code sample RenderingModel
and RenderableDefinition
are both interfaces. As I am aware we can not implement two interfaces in one class, but here this is achieved through some other way. Could someone explain me the technique used in the following line especially:
public class RenderingModelI开发者_运维知识库mpl < RD extends RenderableDefinition >
implements RenderingModel {
Following is the complete class which you may find at magnolia java docs
public class RenderingModelImpl < RD
extends RenderableDefinition >
implements RenderingModel {
protected final RenderingModel parentModel;
protected final Content content;
protected final RD definition;
public RenderingModelImpl(Content content, RD definition, RenderingModel
parent) {
this.content = content;
this.definition = definition;
this.parentModel = parent;
}
public RenderingModel getParent() {
return this.parentModel;
}
public RenderingModel getRoot(){
RenderingModel model = this;
while(model.getParent() != null){
model = model.getParent();
}
return model;
}
public Content getContent() {
return this.content;
}
/**
* Shortname for templates: model.def.
*/
public RD getDef() {
return getDefinition();
}
public RD getDefinition() {
return this.definition;
}
public String execute() {
return null;
}
}
This is Java generics. RD is known as a "type parameter". The "RD extends RenderingDefinition" part means that you can create instances of RenderingModelingImpl parameterized with any class that is a subclass of RenderingDefinition.
Let's say you have class Foo that extends RenderingDefinition, you will be able to make this call...
new RenderingModelImpl<Foo>(...)
This will have the effect that any methods on this instance of RenderingModelImpl that are specified to return RD will return Foo.
For many simpler examples of generics, see Java collections (List, Set, Map, etc) in Java 5 or newer.
You are also not correct regarding not being able to implement two interfaces. A Java class can implement any number of interfaces. It is only subclassing that is restricted to a single base class.
Defining generic type to take parameter for methods or constructor but this generic type must be extended from RenderableDefinition or must be implemet RenderableDefinition. So when you create with new RenderingModelImpl<AnyCLass>();
AnyClass must be extended from RenderableDefinition, other types will not be accepted.
精彩评论