【发布时间】:2019-03-10 18:47:33
【问题描述】:
我有一个问题,对专家来说可能是基本问题。但我不是java专家。所以我不知道也无法在谷歌中找到很多关于这个的细节。 希望有人能帮帮我。
我想从 Main 类中存在的方法访问一个 List,以便在不同包中的不同类的另一种方法中使用。所有访问修饰符都是公共的。这可以在java8中访问吗?
public class Main {
public static void main(String[] args) throws IOException {
initTariffData() ;
....
....
}
public static void initTariffData() {
List<List<Object>> SlotList = null;
.......
.......
for(int innerloop=0; innerloop<(CostList.size());innerloop++) {
newList = new ArrayList<>();
newList.add(PowerList.get(innerloop));
newList.add(DurationsList.get(innerloop));
newList.add(CostList.get(innerloop));
SlotList.add(newList); //Lists of all slots for 7 days
}
}
}
另一个类:
public class MyModel implements TariffModel {
.....
//Here I want to access the List "Slotlist" from the function "initTariffData" in main class
....
}
我希望我的问题很清楚并提供必要的信息。如果还不清楚,请告诉我。
我在 google 上搜索了很多,但没有太多关于从 Main 类中的不同方法访问变量到另一个包类的信息。
【问题讨论】:
-
不,不可能,因为 SlotList 是一个局部变量,而不是一个字段。将其设为字段,您就可以访问它。
-
非常感谢..我现在把它作为你提到的一个字段并且它工作了.. public class Main { public static SmartChargingTariff TariffData;静态 Logger 日志 = LogManager.getLogger(Main.class);公共静态列表
- > SlotList = null; } 公共类 MyModel 实现 TariffModel { Main.SlotList.get(2); .... } 非常感谢!! :)