illegalaccessexception - 如何通过调用另一个类中对象的方法来打印while循环
问题描述
运行应用程序时出现此错误:
线程“主”java.lang.IllegalAccessError 中的异常:WhileLoop 类试图访问字段 LoopClass.x(WhileLoop 位于加载程序 com.sun.tools.javac.launcher.Main$MemoryClassLoader @782663d3 的未命名模块中;LoopClass 位于未命名模块中WhileLoop.main(WhileLoop.java:11) 处的加载程序“应用程序”)
我
public class WhileLoop {
LoopClass loopObj; //bring loopObj as new attribute for the WhileLoop class of type 'CodePractice'
public WhileLoop() { //constructor
}
public static void main(String[] args) {
LoopClass loopObj = new LoopClass();
loopObj.whileLoop(loopObj);
System.out.println(loopObj.x);
}
}
public class LoopClass {
int x;
public LoopClass() {
int x = 1;
}
public static void main(String[] args) {
}
public void whileLoop(LoopClass loopObj) { //pass loopObj as a parameter of whileLoop
loopObj.x = 1;
while (loopObj.x < 5) {
loopObj.x++;
}
}
}
我想通过调用对象上的方法来打印 while 循环的内容。我该怎么做?
解决方案
可以通过将 whileLoop 声明为static
,int x
作为 LoopClass 的参数传递,为其分配值“this.x”,最后调用对象“loopObj”的方法来规避该错误。谢谢萨钦·桑尼。
推荐阅读
- c# - 带有 XAML WPF 的 Powershell 动态运行命令
- node.js - windows10和windows server 2012 nodejs在请求数据中捕获意外令牌
- kotlin - 如何从 TeamCity kotlin DSL 的脚本步骤为 kotlin 变量赋值?
- nfs - ZFS:共享大量数据集
- reactjs - 按需从redux store获取数据(onClick)
- python - 为什么我的 while 循环中的条件在 python 中不起作用?
- iis - IIS7.5 web.config - 如何将路径与查询字符串匹配?
- java - 使用同步(锁定对象)块时,静态锁定对象是否需要是最终的?
- python - pdf布局更改时的pdf文本提取
- html - QTextTableCell 的宽度?