问题
What does dot class mean in the parameter passed to Constructor
I am using jgrapht for the first time . I have this question
What are we passing to the constructor of the DefaultDirectedGraph class? I mean what does DefaultEdge.class means ? There is no static field with that name inside that class. I mean what is actual being passed to the contructor of that class. What does the dot class mean there ?
DirectedGraph<String, DefaultEdge> g =
new DefaultDirectedGraph<String, DefaultEdge>(DefaultEdge.class);
回答1:
If the question only aims at the syntax, you might want to refer to the section The .class Syntax of the site about Retrieving Class Objects from the oracle documentation. In general DefaultEdge.class
is an object that represents the class DefaultEdge
. This is an object of the type java.lang.Class, and contains information about the class itself - e.g., which fields and methods this class contains.
In this case, this Class
object is used internally, by jgrapht, in order to create instances of edges. When the Graph#addEdge(V,V) method is called, this Class
object will be used internally to create an edge - particularly, to create a DefaultEdge
instance.
There are various possible ways how this can be done exactly, but it will either boil down to calling Class#newInstance(), or to obtaining a Constructor
from the given Class
and invoking Constructor#newInstance(...), passing the given vertices as parameters.
Extended in response to the comment:
For the particular case of the DefaultDirectedGraph
, the creation of the edges is done with an EdgeFactory
- a simple Factory that creates edge instances from two vertices. This factory is used in the addEdge
method:
@Override public E addEdge(V sourceVertex, V targetVertex)
{
...
E e = edgeFactory.createEdge(sourceVertex, targetVertex);
...
}
This EdgeFactory
is created in the constructor, from the given Class
object (which may be DefaultEdge.class
, as in the example) :
public DefaultDirectedGraph(Class<? extends E> edgeClass)
{
this(new ClassBasedEdgeFactory<V, E>(edgeClass));
}
The ClassBasedEdgeFactory
, in turn, does what I already mentioned: It uses the given Class
object to create a new instance:
public class ClassBasedEdgeFactory<V, E> implements EdgeFactory<V, E>, ...
{
...
private final Class<? extends E> edgeClass;
public ClassBasedEdgeFactory(Class<? extends E> edgeClass)
{
this.edgeClass = edgeClass;
}
...
@Override public E createEdge(V source, V target)
{
try {
return edgeClass.newInstance();
} catch (Exception ex) {
throw new RuntimeException("Edge factory failed", ex);
}
}
}
So to summarize: One can pass a Class
to the graph constructor (for example, DefaultEdge.class
), to simply tell him: "Whenever I want to add a new edge, then create a new instance of this edge class."
来源:https://stackoverflow.com/questions/30750236/what-does-defaultedge-class-mean-in-jgrapht-example