0

I have a class HDFSHbaseInstance which will load Hbase config in static block

public class HDFSHbaseInstance {
    private static FileSystem hadoopFS = null;
    private static Configuration config = null;
    static {
        try {
            config = HBaseConfiguration.create(new Configuration());
            config.set("hbase.zookeeper.quorum", "10.21.1.111");
            config.set("hbase.zookeeper.property.clientPort", "1234");

            hadoopFS = FileSystem.get(config);
        }
        catch (IOException e) {
            ...
        }
    }
// remaining code
}

Now for some reasons, I have to create one more class HDFSInstance which will load Hadoop default config

public class HDFSInstance {
    private static FileSystem hadoopFS = null;
    private static Configuration config = null;
    static {
        try {
            config = new Configuration();
            hadoopFS = FileSystem.get(config);
        }
        catch (IOException e) {
            ...
        }
    }
// remaining code which is same as upper class
}

Problem is here, I have a class which will decide to use anyone above class based on some condition. I am simply doing it through conditional statement like

public class A{
    main(){
        if (defaultConf) { HDFSInstance.callFun(); }
        if (hbaseConf) { HDFSHbaseInstance.callFun(); }
    }
}

Questions

  1. Is there a way to combine both HDFSInstance and HDFSHbaseInstance into one by adding conditional statement in static block?
  2. I thought of static constructor but it wouldn't work in my present scenario, So Is there a solution without creating constructor?
Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
Shashank Gb
  • 902
  • 1
  • 6
  • 14
  • 1
    you can use `Factory design pattern`. Read about it https://www.geeksforgeeks.org/factory-method-design-pattern-in-java/ – Prog_G Jul 19 '22 at 13:47
  • It's a cool method. Factory design pattern requires objects needs to be created. since `HDFSHbaseInstance` has been used in so many places. I can't implement it. Any other suggestions? – Shashank Gb Jul 20 '22 at 12:12

1 Answers1

0

That would be really bad design. At the very least move your static block to be a static method and in your checking flag invoke appropriate method. But really you should use a Factory pattern and fetch the appropriate class based on the value of your flag. I just answered similar question in detail. Please see my answer on this question: How to us a custom ClassLoader to get different and new objects from a library in Java

Michael Gantman
  • 7,315
  • 2
  • 19
  • 36