简体   繁体   中英

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

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?

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 (u sing 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

您可以将变量设置为全局变量,但将访问权限更改为private,然后使其getter和setter方法在其他类中访问它们。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM