2

In my generic class I need to restrict type parameter to Integer OR String. Is there a way to achieve this? I cannot use T extends SomeClass to limit types, because common parent is just Object...

update

public abstract class MyClass<T>{

    private T value;

    public T getValue(){
        return value;
    }
}

I'd like the value type to be a String or an Integer and I need to use the same method to get it (not getIntValue() + getStringValue() )

This doesn't seem to help...

davioooh
  • 23,742
  • 39
  • 159
  • 250
  • See this answer here: http://stackoverflow.com/questions/8330370/generic-or-instead-of-and-t-extends-number-charsequence – Hegi Feb 17 '14 at 09:50

2 Answers2

3

If I were you, I would overload two methods:

public void withInteger(Integer param) { .. }

public void withString(String param) { .. }

Note that there's no reason to use something like T extends String, because both String and Integer are final and can't be subclassed.

Konstantin Yovkov
  • 62,134
  • 8
  • 100
  • 147
0

Just made your class ctor private and pass through a factory method to create implementation; type restriction is not bounded to MyClass but via factory.

class MyClass<T> {
  private T value;

  MyClass(T value) { this.value = value; }
  public T getValue() { return value; }
}

class MyClassFactory {
  public final static MyClass<Integer> createInteger(Integer i) {
    return new MyClass<Integer>(i);
  }
}
Luca Basso Ricci
  • 17,829
  • 2
  • 47
  • 69