Reputation: 95
I am trying to write a method that gets an object from a database. This method must be able to specify what class that object expected to be (like: get("some.key", Integer.class)
will return an integer).
However, if the expected type is an integer, and our value is a string, I would like it to cast that string to an integer and return that.
My current code looks like this:
public <T> T get(String key, Class<T> type) {
Object element = ...;
if (type == Integer.class && element instanceof String) return Integer.parseInt((String) element);
return element;
}
However, my IDE is giving me an error: when returning Integer.parseInt((String) element)
, the method expects a return type of type T
, but I am returning an Integer, which in that case is type T
, but it won't accept this.
I have tried to cast it like so: (T) Integer.parseInt((String) element)
, but my IDE says that those are inconvertible types.
How can I make it so that this method will return a valid object of type T
after parsing the Integer?
Any help is appreciated.
Upvotes: 0
Views: 54
Reputation: 269797
Cast your result to T
using the Class
instance you are passed.
public <T> T get(String key, Class<T> type) {
Object element = ...;
if (type == Integer.class && element instanceof String) element = Integer.parseInt((String) element);
return type.cast(element);
}
Upvotes: 3