Reputation: 1646
I want to create dynamic references to my Socket in the program below so that I can save different references to the my Socket object while saving it in map.
So first time the reference of Socket class should be created with socket1 and then for the next time it should be created with socket2 and so on dynamically. I tried appending the reference with socket + a and tried creating the reference with this name, but it did not work. Is there a way to create dynamic reference to the objects
int a = 0;
public static void connect(int portNo, int trgtPNo , String webN)
{
try {
String x = Inet4Address.getLocalHost().getHostAddress().toString();
InetAddress addr = InetAddress.getByName(x);
String sock = "socket" + a;
Socket sock = new Socket(webN, trgtPNo , addr , portNo);
a++;
map.put(portNo,sock);
} catch (Exception e) {
e.printStackTrace();
}
}}
Any lead would be helpful.
Upvotes: 0
Views: 428
Reputation: 61
You can't dynamically set variable names when the program is running. the variable name determined only when you write the code.
Instead, you can set an Array
of instances of the Socket. for example, to create 10 instances:
try {
int socketsNum = 10;
String x = Inet4Address.getLocalHost().getHostAddress().toString();
InetAddress addr = InetAddress.getByName(x);
Socket[] sockets = new Socket[socketsNum];
for (Socket s : sockets) {
s = new Socket(webN, trgtPNo , addr , portNo);
}
} catch (Exception e) {
e.printStackTrace();
}
Then, you can get Socket instance with his index number, for example socket[5]
.
If you don't want to determined the number of instances in advance, you can use ArrayList()
instead of Array
.
Upvotes: 1