Forgive me if this is trivial or impossible, but I have a moment on Monday morning.
I would like to create a method that implements some methods from the Gson
library to load some parameters of Objects. Basically, I have a bunch of different settings objects, but I don’t want to get used to overriding the loading method for each class so that I want to have something like:
public class ConfigLoader { public static void main(final String[] args) { final ConfigurationSettings loadedConfigSettigs = load("testSettings.json", ConfigurationSettings.class); final AlternativeConfigurationSettings alternativeConfigSettigs = load("testSettings2.json", AlternativeConfigurationSettings .class); } public T load(final InputStream inputStream, final Class<T> clazz) { try { if (inputStream != null) { final Gson gson = new Gson(); final BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); return gson.fromJson(reader, clazz); } } catch (final Exception e) { } return null; } }
where I can pass in the InputStream
and the class of the object I want to return. Is there an easy way to do this (I don’t want to create a method for every class that I want to load, and also don’t want to create a specific loader for each class)?
source share