Java Singleton内部类错误理解
我在过去的两个月里一直在编程
Java,但我在python和C中经验过程序员.我知道我因此而犯了错误.
我来到这个问题清除警告我在Android工作室的项目. 我使用带有内部类的Singleton类将所有配置参数保存在一个位置,让所有其他类访问它而不需要传递配置. 这是我的Singleton的基本代码 public class syscfg { public List<CommData> Commlist; public static CommConfigIP4 MyCommConfig;// = new CommConfig(); private static syscfg instance = null; private static boolean ConfigStat = false; /** JAVA singleton control methods**/ protected syscfg(){ // pues eso if(ConfigStat == false){ Log.i("SD_app_log","SYSCFG: Module Initialization"); ConfigStat = true; MyCommConfig = new CommConfigIP4(); init_config(); }else{ Log.i("SD_app_log","SYSCFG: Module Loaded"); } } public static syscfg getInstance(){ if(instance == null){ instance = new syscfg(); } return instance; } public class CommConfigIP4{ public int discoveryPort = 30303; public byte[] MyMAC; public String MyType = ""; public String MyIP; public byte[] getIPbytearray(){ // byte[] IPout= new byte[4]; try{ byte[] IPout = (InetAddress.getByName(MyIP)).getAddress(); return IPout; }catch (Exception e){ return null; } } 在我的通讯java文件/类中我有: public class Communications { private syscfg CFid ; ... public Communications(Context ctx){ ... CFid = syscfg.getInstance(); init_comms(); //init_comms calls whoami } private void whoami (){ ... CFid.MyCommConfig.MyType = netint.getName(); ... } } 所以,当我第一次拥有syscfg中的所有元素(变量,类和方法)时,静态android工作室会显示一条警告,说静态成员通过实例引用访问.经过一些研究和文档后,我发现建议不要使用静态变量和方法,我试图将它们全部消除.但后来我得到了一个nullpointexception错误 CFid.MyCommConfig.MyType = netint.getName(); 使用调试器,我发现CFid.MyCommConfig = null 我使用单例来避免在syscfg类上使用static并通过实例化访问而不使用类名. 现在我的单例代码就像这里发布的CommConfigIP4静态代码一样,我再次发出警告,建议我使用: syscfg.MyCommConfig.MyType = netint.getName(); 而不是使用实例来访问配置. 这里发生了什么?我错过了什么? 谢谢, 解决方法
在你的whoami()方法中,你做了这个引用:
CFid.MyCommConfig.MyType = netint.getName(); …但是,“MyCommConfig”是类“syscfg”的静态属性,而变量“CFid”是指此类的实例.换句话说,“syscfg”的所有实例(以及类定义本身)都引用了“MyCommConfig”变量的相同副本(这是静态的意思). 因此,通过说“syscfg.MyCommConfig”来引用“MyCommConfig”变量并不那么令人困惑,因为这表明你指的是静态变量而不是实例1. 顺便说一句,您应该考虑遵循标准Java代码约定来大写类名和变量,因为这将使您的代码对其他Java程序员更具可读性. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |