Is there a way to Implement conditional statements in Static Block

330 Views Asked by At

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?
1

There are 1 best solutions below

0
Michael Gantman On

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