How to Access local variable of the method from one class to another

Viewed 64
public void processVmCreate(SimEvent ev) {
    int[] data = (int[]) ev.getData();
    int datacenterId = data[0];
    int vmId = data[1];
    int result = data[2];
}

I want to access the local variable of method processVmCreate(SimEvent ev) in another class that is in another package. How can i access?

3 Answers

Local variables die after the method execution is done.

If you want to use them in other method, your choices are :

1) Pass to that method, assuming you calling that method here (using it's instance may be or with in the same class method).

2) Creating static variable and assign here , so it avail there. But make sure that you call this method before using it. but I prefer the first. Unless you have no option choose the static.

To get your results from another class, you can :

1 - Declare them as global attributes and access to them by their getters like this:

public class YourClass {

    int datacenterId = -1;
    int vmId = -1;
    int result = -1;


    public void processVmCreate(SimEvent ev) {
        int[] data = (int[]) ev.getData();
        datacenterId = data[0];
        vmId = data[1];
        result = data[2];
    }

    public int getDatacenterId() {
        return datacenterId;
    }


    public int getVmId() {
        return vmId;
    }

    public int getResult() {
        return result;
    }

}

2- Or you can transform your method like this and let it return a hashMap :

   public HashMap<String, Integer>  processVmCreate(SimEvent ev) {
        int[] data = (int[]) ev.getData();
        HashMap<String, Integer> map = new HashMap<>() ; 
        map.put("datacenterId", data[0]) ;
        map.put("vmId", data[1]) ;
        map.put("result", data[2]) ;
        return map ;
    }

And from another class you can access to your attributs like this :

 public class AnotherClass {
         //other code 
        public void anotherMethod(){
            YourClass yourClass = new YourClass() ;
            int datacenterId = yourClass.processVmCreate(simEvent).get("datacenterId") ;
            int vmId yourClass.processVmCreate(simEvent).get("vmId") ;
            int result yourClass.processVmCreate(simEvent).get("result") ;

        }
    }

Unless , you can not access to local variable from another class because they are local

You can make the variables global but change the access to private and make their getter and setter methods then access them in other class.

Related