user2731629
user2731629

Reputation: 412

Java Generics - Define Method only accepts List or Maps

I have defined a method in Java like below

public void processData(Object input) {
if(!(input instanceof List || input instanceof Map)) {
      throw new RuntimeException("Invalid argument type. method accept only Map type or List type");
    }

if(input instanceof List) {
//Do something
} else if(input instanceof Map) {
//Do Something
}
}

The above method just works fine. But is there a way to use generics here to show compile time error if user tries calls the method with unexpected argument? Method that only accepts List or Map ? <T extends Collection> wont work because Map is not part of Collection. Is there any other way ?

Upvotes: 1

Views: 420

Answers (1)

Marc
Marc

Reputation: 3285

The answer is no. The only common super class between Map and List is Object. As others mentioned in the comments, you could simply create two methods, one that accepts a List and another that accepts a Map:

public void processData(List input) {
    // Do something
}

public void processData(Map input) {
    // Do Something
}

Upvotes: 3

Related Questions