3
I need to change the value of a variable dynamically by passing it as a parameter by an auxiliary method. I have always used the values of the parameters by moving from right to left. It is possible to change the variable from left to right:
Fields of my class:
private String ipAddress;
private String dnsAddress;
Set method to assign value to variable:
public void setDHCP(){
cmdAdress(ipAddress,"address", "dhcp");
cmdAdress(dnsAddress, "dnsservers", "dhcp");
}
Auxiliary method to make set dynamic:
private void cmdAdress(String address, String type, String adresses){
//Isso não funciona
address = "netsh interface ip set ";
//Isso funciona mas não me é útil
//ipAddress = "netsh interface ip set ";
//restante do código
address += type;
address += " name = \"" + adapterName + "\" ";
address += adresses + " ";
}
The expected value would be something like this:
ipAddress: netsh interface ip set address name = \"OffBoard\" static 192.168.1.220 255.255.255.0 192.168.1.1
dnsAddress: netsh interface ip set dnsservers name=\"OffBoard\" static 192.168.1.1 primary no
Although you get no error, the value of the fields are always empty. I am doing something wrong or demanding something that is not the language?
You are not passing the attributes themselves, just copying their value to the method
cmdAdress
.– user28595
Is it possible to pass the attribute? I’ve tried this cmdAdress(Object address, String type, string Addresses). It also doesn’t work.
– Vanderlei
Just calling the attribute straight in the method, as you did and commented that it was not useful, but using primitive types and String, is the only way.
– user28595
Then I will have to create two auxiliary methods: one to set each attribute. Correct?
– Vanderlei
Why not directly change the class attribute? Why pass the attribute itself as a parameter to a class method?
– user28595
The intention was to leave the dynamic method without having to duplicate it. The parameters are of the same type, so I thought I would avoid creating a method for each variable or avoid having to create a switch or if to determine which variable I would be dealing with.
– Vanderlei
If there is need to identify whether it is an ipaddress or dnsAddress, unfortunately you will have to make use of it. I would use constants to identify the type, and pass it as a parameter, so you can treat more simply which of the two information is being received.
– user28595