How to resolve overload method using generic ( java )

Viewed 93
public void put(String str);
public void put(Integer in);
public void put(Boolean bol);

public <T> void putGeneric(T value)
{
    put(value);
}

This code show error "can not resolve method"

4 Answers

T is one of String, Integer, Boolean

Based on these requirements, you cannot enforce this at the class level using generics.

If you want to be able to pass though these three types, you can use a cascaded try-catch and only allow a string representation of those types

For example,

void putGeneric(String s) { 
  try { 
    int i = Integer.parseInt(s); 
    put(i);
  } catch (NumberFormatException e) { 
    if (s.matches("true|false") {
      put(Boolean.parseBoolean(s));
    } else {
      put(s); 
    }
  }
}

More specifically, you need to coerce the types into the specific methods

Here T is generic type and the JVM is also confused to which type it should resolve . This functionality should be better implemented having one method called Put and which accepts generic type as the operations is common for all types .

Generics are used where functions do same work regardless to the input parameter , lets say add(x,y) method will add Integers , double... this type of method definition requires generic implemented .

The error is shown because you don't have any method that accepts every Object so no method is fitting.

You need to exactly tell Java what value is:

public void put(String str);
public void put(Integer in);
public void put(Boolean bol);

public <T> void putGeneric(T value) {
    if (value instanceof String) put((String) value);
    else if (value instanceof Integer) put((Integer) value);
    else if (value instanceof Boolean) put((Boolean) value);
    else throw new IllegalArgumentException("value has wrong type. Type: " + T + " value: " + value);
}

Or just leave the put()-methods public and access them directly.

Your putGeneric method is generic not put method. Therefore before calling the put method you need to typecast the object.
you can call put as below:

public <T> void putGeneric(T value) {
        if (value instanceof String) {
            put((String) value);
        } else if (value instanceof Integer) {
            put((Integer) value);
        } else if (value instanceof Boolean) {
            put((Boolean) value);
        } else {
             throw new ClassCastException("unsupported class!!!");
        }

    }
Related