2

I have a method which accepts two values and converts it into key-value pair of a map and returns it to the calling method. The key is always String but the value can be of any Class. I can't seem to convert the value into generic while accepting in method signature. Here's my code:

private Map<String, Class<T>> mapBuilder(String key, T value) {
        Map<String, Class <T>> map = new HashMap<>();
        map.put(key, value);
        return map;
    }

Can someone tell what can be done instead?

1
  • Why not use String key, Class<T> value as the method params and call this method invoking .class on the params before passing them to the method? Commented Jul 23, 2020 at 17:52

2 Answers 2

1

Are you sure you want to have a map with Class as a value? If so, you have firstly define a generic type parameter <T> either at the class level (public class MyClass <T> { ... } or at the method level:

private <T> Map<String, Class<T>> mapBuilder(String key, T value) {
    Map<String, Class <T>> map = new HashMap<>();
    map.put(key, (Class<T>) value.getClass());
    return map;
}

Note the following:

  • As long as you want to add an instance of Class<T> to the map as a value, you have to get it from the T object.
  • There is a problem with the type incompatibility as long as getClass returns Class<?>, so an explicit casting is needed (also in the snippet above).

Finally, I'd prefer a solution with the wildcard parameter:

private Map<String, Class<?>> mapBuilder(String key, T value) {
    Map<String, Class <?>> map = new HashMap<>();
    map.put(key, value.getClass());
    return map;
}
Sign up to request clarification or add additional context in comments.

Comments

0

The Class is too much. T already refers to the type:

private <T> Map<String, T> mapBuilder(String key, T value) {
   Map<String, T> map = new HashMap<>();
   map.put(key, value);
   return map;
}

Class<T> would refer to the class-object of T

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.