I create a Preferences class and for the Getters I wan't to use Runtime-Type Token.
So here is my getter method:
public <T> T get(String key, Class<T> clazz) {
// do some crazy stuff (e.g. Double <-> Float)
}
Up to that, everything works fine. But I would like that the class parameter will be optional.
boolean b = preferences.get(key);
So I add an additional method:
public <T> T get(String key) {
// return get(key, Class<T>);
}
Now the Question: Is there a way to do that? Is there a way to get an/the instance of Class<T>
.
It's possible with a small workaround:
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");
Forces clients to create a subclass of this class which enables retrieval the type information even at runtime.
A generic type is like a template. You cannot create instances of it unless you specify real types for its generic type parameters. To do this at run time, using reflection, requires the MakeGenericType method.
What Does Class Mean? A class — in the context of Java — is a template used to create objects and to define object data types and methods. Classes are categories, and objects are items within each category. All class objects should have the basic class properties.
getClass() method returns the runtime class of an object. That Class object is the object that is locked by static synchronized methods of the represented class.
You can't. But if you want to class parameter to be optional, simply pass null
and check if it's not null when you use it.
If you want to infer it from the left-hand side - it's not possible.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With