How can I instantiate a generic type in Java?

后端 未结 6 861
遥遥无期
遥遥无期 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:55

    Try this:

    protected  T getProperty(String key, T fallback) {
        String value = properties.getProperty(key);
    
        if (value == null) {
            return fallback;
        } else {
            Class FallbackType = fallback.getClass();
            return (T)FallbackType.cast(value);
        }
    }
    

提交回复
热议问题