Java – get an instance of class [runtime type token]
•
Java
I created a preferences class. For getters, I don't want to use runtime type token
So this is my getter method:
public <T> T get(String key,Class<T> clazz) { // do some crazy stuff (e.g. Double <-> Float) }
So far, everything is normal But I want the class parameter to be optional
boolean b = preferences.get(key);
So I added an additional method:
public <T> T get(String key) { // return get(key,Class<T>); }
Now question: is there a way to do this? Is there any way to get an instance of / < T >
There is a small solution:
public <T> T get(String key,T... args) { return get(key,(Class<T>) args.getClass().getComponentType()); } public <T> T get(String key,Class<T> clazz) { System.out.println("key : " + key); System.out.println("clazz: " + clazz); } // using Boolean b = get("mykey");
Solution
You can't But if you want to set the class parameter to optional, just pass null and check whether it is null when you use it
If you want to infer it from the left - it's impossible
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码