私はJavaを独学しようとしているので、これが正しいかどうかはわかりません。メイン メソッドを含むクラスがあり、このクラス内には、java.util.Properties を使用してユーザー設定にアクセスする必要があるいくつかのサブクラスがあります。プロパティ オブジェクトを機能させるには、すべてのサブクラスでプロパティ オブジェクトを作成する必要があります。configFilePath を使用してオブジェクトを参照することはできません。null でなければなりません。親クラス内でこのパブリック オブジェクトを作成できるかどうか疑問に思っているので、そのすべてのサブクラスで作成する必要はありませんか? これが私のコードです。動作しますが、これを正しく行っているかどうかは本当にわかりません。
public class Frame1 extends JFrame {
Settings config = new Settings(); //this is the object I want to reference within subclasses
class Update extends SwingWorker<Integer, Void> { //first subclass
@Override
protected Integer doInBackground() throws Exception {
Settings config = new Settings(configFilePath); //yet I have to create the object within every subclass, this time an argument is required.
String templateDir = config.getProperty("templatedir");
String writePath = config.getProperty("outputdir");
//do some logic code, not required for my question
}
@Override
protected void done() {
Update2 update2 = new Update2();
update2.execute(); //start the next subclass which also needs access to Settings(configFilePath)
}
}
}
public class Settings extends JFrame {
String configFilePath = "C:/path/to/settings.properties";
Properties properties = new Properties();
public Settings(String configFilePath) throws IOException {
this.configFilePath = configFilePath;
FileInputStream fis = null;
try {
fis = new FileInputStream(configFilePath);
properties.load(fis);
} catch (FileNotFoundException e) {
setDefaults();
} finally {
if (fis != null) {
fis.close();
}
}
}
}
これを正しく行っているかどうかはわかりませんが、機能しているように見えますが、ユーザー設定にアクセスする必要があるたびに構成オブジェクトを作成する必要があるのはかなり冗長なようです。これが以前に尋ねられていないことを願っています。見つけられなかったので、リンクしてください。