0

I want to write method that would accept parameter of types a.A or b.B. Currently it's implemented:

import a.A;
import b.B;

...
public void doSth(A arg) {
      SpecificClass.specificMethod(arg);
}

public void doSth(B arg) {
      SpecificClass.specificMethod(arg);
}

I want to have one generic method "doSth" that use wildcards and accepts only a.A or b.B. Important information a.A and b.B aren't subtypes of each other. The only common type is java.lang.Object.

Any help?

bontade
  • 3,194
  • 6
  • 48
  • 75

3 Answers3

1

Assuming you could do that, if A and B have no common superclass, you won't be able to call any methods on the arguments but Object's methods.

So I think the only 2 reasonable solutions are:

  • have two methods, one for A and one for B (your current setup)
  • have one method that takes an Object as a parameter, check that the argument is an instanceof A or B, and if not throw an IllegalArgumentException
assylias
  • 321,522
  • 82
  • 660
  • 783
  • I'm not sure if there's no way to do this with wildcards. I saw that there's used often `&` sign that restrict argument has to implements/extends both `A & B` classes. So maybe it possible to do this with `|` but I don't know how... – bontade Sep 15 '12 at 10:18
  • 2
    @bontade Generics can be defined as an intersection of types (using `&`) but not as a union of types. For the fine prints, you can have a look at the [JLS 4.4](http://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html#jls-4.4-200). – assylias Sep 15 '12 at 10:21
1

You may wrap both A and B extending a common interface, just like:

interface CommonWrapper {
  public void doSth();
}

public class AWrapper implements CommonWrapper {
  private A wrapped;
  public AWrapper(A a) {
    this.wrapped = a;
  }

  public void doSth() {
    // implement the actual logic using a
  }
}

public class BWrapper implements CommonWrapper {
  private B wrapped;
  public BWrapper(B b) {
    this.wrapped = b;
  }

  public void doSth() {
    // implement the actual logic using b
  }
}

Then modify your method doSth to accept a CommonWrapper object as parameter:

public void doSth(CommonWrapper c) {
  c.doSth();
}
Roy Ling
  • 1,592
  • 1
  • 14
  • 31
0
public <T> void doSth(T arg) {
      SpecificClass.specificMethod(arg);
}

will be called :

yourClass.doSth(yourarg);

But it doesn't restrict to anything that can extend object, whats the point everything does.I would suggest having both your classes implement a common interface and then program to that interface.

NimChimpsky
  • 46,453
  • 60
  • 198
  • 311