0

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?

  • That's not possible. Generics are purely for sanity checks at compile time. They don't exist at runtime, so the code would make no sense to the JVM. Could you explain what you're trying to accomplish? It may be that overloading the method can solve the problem. – 4castle Oct 27 '16 at 01:29

1 Answers1

1

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);
    //...
}
Mark
  • 2,167
  • 4
  • 32
  • 64