如何从Java中的静态方法访问非静态成员?

编程入门 行业动态 更新时间:2024-10-25 14:31:36
本文介绍了如何从Java中的静态方法访问非静态成员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一种情况,我必须从静态方法内部访问非静态成员.我可以使用新实例访问它,但是当前状态将丢失,因为非静态成员将被重新初始化.如何在不丢失数据的情况下实现这一目标?

I have a situation where i have to access a non static member from inside a static method. I can access it with new instance, but current state will be lost as non static member will be re-initialized. How to achieve this without losing data?

推荐答案

也许您想要单人.然后,您可以从静态方法中获取该类的(唯一)实例并访问其成员.

Maybe you want a singleton. Then you could get the (only) instance of the class from within a static method and access its members.

基本思想是

public class Singleton { private static Singleton instance = null; private Singleton() {} public static Singleton getInstance() { if (instance == null) { instance = new Singleton(); } return instance; } }

,然后使用某些静态方法:

and then in some static method:

public static someMethod() { Singleton s = Singleton.getInstance(); //do something with s }

更多推荐

如何从Java中的静态方法访问非静态成员?

本文发布于:2023-07-15 10:18:25,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1110626.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:静态   成员   方法   Java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!