How can I instantiate a generic type in Java?

后端 未结 6 854
遥遥无期
遥遥无期 2020-12-17 16:26

I\'ve added a human-readable configuration file to my app using java.util.Properties and am trying to add a wrapper around it to make type conversions easier. Specifically,

6条回答
  •  南方客
    南方客 (楼主)
    2020-12-17 16:57

    The following uses functional interfaces.

    You could change the method signature to use a provided "parser":

    protected  T getProperty(String key, T fallback, Function parser) {
        String value = properties.getProperty(key);
    
        if (value == null) {
            return fallback;
        } else {
            return parser.apply(value);
        }
    }
    

    Also, for efficiency you might want to replace T fallback with Supplier fallbackSupplier to prevent having to create fallback values when they are not needed:

    protected  T getProperty(String key, Supplier fallbackSupplier, Function parser) {
        String value = properties.getProperty(key);
    
        if (value == null) {
            return fallbackSupplier.get();
        } else {
            return parser.apply(value);
        }
    }
    

    Then you can use method references and lambda expressions as parser and fallback supplier, e.g.:

    protected void func2() {
        foobar = getProperty("foobar", () -> 210, Integer::valueOf);
        // Better create own parsing method which properly handles 
        // invalid boolean strings instead of using Boolean#valueOf
        foobaz = getProperty("foobaz", () -> true, Boolean::valueOf);
    
        // Imagine creation of `ExpensiveObject` is time-wise or 
        // computational expensive
        bar = getProperty("bar", ExpensiveObject::new, ExpensiveObject::parse);
    }
    

    The advantage of this approach is that it is not restricted to a (potentially non-existent) constructor anymore.

提交回复
热议问题