我可以在Java中的构造函数中调用方法吗? [英] Can I call methods in constructor in Java?

查看:194
本文介绍了我可以在Java中的构造函数中调用方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



假设我有一个名为的方法, readConfig(),读取配置并将其放入 Map 对象中。当程序需要使用配置值时,它使用它的define键读取对象。我想知道构造函数只调用一次它的生命周期。我可以把我的方法 readConfig()到构造函数中,这将给我一次调用的好处,还是有另一种机制来做这件事?

解决方案

更好的设计将是

  public static YourObject getMyObject文件configFile){
//进程并创建一个对象配置它并返回它
}


$ b b


I have situation, where I want to read configuration file only one time, when class is instantiated.

Suppose I have a method named readConfig(), that reads configuration and puts it into a Map object. When the program is required to use configuration value it reads object with it's define key. I want to know that constructor calls only once it's life cycle. Can I put my method readConfig() into constructor, which would give me benefit of one time calling or is there another mechanism to do that?

解决方案

Better design would be

public static YourObject getMyObject(File configFile){
    //process and create an object configure it and return it
}

这篇关于我可以在Java中的构造函数中调用方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆