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

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

问题描述

我的情况是,当类被实例化时,我只想读取一次配置文件.

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

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

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?

推荐答案

更好的设计是

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

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

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