Java : What to add for Class Type arguments?
I am working on simulating wireless sensor network. I have to create a nodes in the simulation.
Functions to create nodes is defined in class Simulator
. Here Simulator
and RadioModel
are two user defined classes.
For creating a node , I have a pre-defined function i.e. createNode()
defined within Simulator
class. It has following syntax:
Node createNode(Class nodeClass, RadioModel radioModel, int nodeId,
double x, double y, double z)
Here I am fine with RadioModel
parameter and all other arguments except "Class nodeClass"
are working fine. What to substitute for this argument i.e. nodeclass
?
Any help will be of great use....
Yes dacwe, as you said Node class is extended by Mica2Node class which I am instantiating. And I have passed the argument as
sim1.createNode(Mica2Node.class, g, nodeId,x,y,z);
Here sim1 is an object of class Simulator and g is an object of class Ra开发者_开发技巧dioModel. Beacause createNode is not a static method, I called it through object. But I am facing three other warnings: from other class i,e. Application.java
public Application(Node node){
this.node = node;
node.addApplication(this);
}
here it is showing error in addApplication(this) method. This method is defined in Node.java as below:
public void addApplication(Application app){
app.nextApplication = firstApplication;
firstApplication = app; }
And the error is as below:
Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - Erroneous sym type: ()void at net.tinyos.prowler.Application.(Application.java:31) at net.tinyos.prowler.TestBroadcastNode$BroadcastApplication.(TestBroadcastNode.java:36) at net.tinyos.prowler.TestBroadcastNode.main(TestBroadcastNode.java:118)
Please help me out......
Are you looking for something like this?
public <T extends Node> T createNode(Class<T> clazz, RadioModel radioModel,
int nodeId, double x, double y, double z);
Which can be used like
RadioModel radioModel = ...
MyNode node = createNode(MyNode.class, radioModel, 1, 2, 3);
Another approach might be to create a factory which encapsulates the creation of all node types, e.g.,
public interface NodeFactory {
public MyNode createMyNode(..);
public YourNode createYourNode(..);
}
It is (proably) whay kind of class the createNode
method should create.
You have some "node classes" that extend Node
(in the example below BigNode
and SomeOtherNode
). So you use the class information to create one of those.
The calling part:
Node created = Simulator.createNode(BigNode.class, radioModel, nodeId, x, y, z);
The implementation of createNode
:
Node createNode(Class nodeClass, RadioModel radioModel, int nodeId,
double x, double y, double z) {
if (nodeClass.equals(BigNode.class))
return new BigNode(radioModel, nodeId, x, y, z);
if (nodeClass.equals(SomeOtherNode.class)) {
return new SomeOtherNode(.....);
throw new IllegalArgumentException("could not create node of type " +
nodeClass);
}
精彩评论