Zodiac Zubeda Zodiac Zubeda - 1 year ago 71
Java Question

How to create a Generic Method with a wildcard type in a set of types?

How can you create a generic class/method that excepts generic types in a list of types? This is the pseudo code of what I want:

class Foo {
Object arrayOfTypes[] = {Integer, Double, Boolean};

public <T in arrayOfTypes> void Bar() {

So, T has to be either an Integer, Double, or Boolean. Also, the only classes that can be used are from a library, so I can't edit them to extend certain classes and do something like
<T extends Car>
. Is there a way to do this?

Answer Source

Your requirement doesn't make sense for generics. If you want a method to accept a variable of one of the types and these types don't share a common superclass or implement a common interface (except for extending Object) you should do:

public void bar(TypeOne t) { /*...*/ }

public void bar(TypeTwo t) { /*...*/ }

public void bar(TypeThree t) { /*...*/ }

by taking advantage of overloading. If there is nothing in common for your 3 types then there is no way a single method can accommodate all of them anyway (with or without generics).

Because 4castle said the same thing in a comment a few minutes before me I feel I need to give a bit more.

A generic method would make sense when there's something in common between your types. So let's say all your types implement a common interface called Common which declares a method String do(int i). Then you can write a method

public void <T extends Common> bar(T instance) {

    String result = instance.do(3);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download