带反射的 NPE
我正在尝试运行客户端并访问字段来设置/获取值。当脚本启动时,我创建一个加载了 URLClassLoader
的客户端类的新实例,并将其分配给 gameApplet
。
现在,下一段代码工作正常(访问静态字段):
Class<?> clientClass = clientClassLoader.loadClass("client");
fps = clientClass.getDeclaredField("fpsOn");
fps.setAccessible(true);
fps.set(null, true);
但是,当我尝试访问非静态字段时:
logged = clientClass.getField("loggedIn");
logged.set(gameApplet, true);
我收到此错误
java.lang.NullPointerException
at sun.reflect.UnsafeFieldAccessorImpl.ensureObj(Unknown Source)
at sun.reflect.UnsafeBooleanFieldAccessorImpl.set(Unknown Source)
at java.lang.reflect.Field.set(Unknown Source)
at launch.run(launch.java:206)
at java.lang.Thread.run(Unknown Source)
,我假设它的实例为空,但为什么它会得到静态场?
I am trying to run a client and access fields to set/get values. As the script starts, I create a new instance of the client class loaded with URLClassLoader
and assign it to gameApplet
.
Now, the next piece of code works fine (Accessing a static field):
Class<?> clientClass = clientClassLoader.loadClass("client");
fps = clientClass.getDeclaredField("fpsOn");
fps.setAccessible(true);
fps.set(null, true);
But then, when I try to access a non static field:
logged = clientClass.getField("loggedIn");
logged.set(gameApplet, true);
I get this error
java.lang.NullPointerException
at sun.reflect.UnsafeFieldAccessorImpl.ensureObj(Unknown Source)
at sun.reflect.UnsafeBooleanFieldAccessorImpl.set(Unknown Source)
at java.lang.reflect.Field.set(Unknown Source)
at launch.run(launch.java:206)
at java.lang.Thread.run(Unknown Source)
I'm assuming it's the instance that is null, but why would it then get a static field?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您似乎没有创建该类的“实例”。您需要调用类的构造函数,然后在需要时使用实例。
上面的代码适用于静态字段,因为它们可以从类访问,即它们不需要实例。
You don't seem to be creating 'instance' of the class. You need to invoke the constructor of the class and then use the instance where required.
Above code works for static fields as they are accessible from class i.e they don't require an instance.