Home > DeveloperSection > Forums > Method argument of different types
Lady Bird Johnson
Lady Bird Johnson

Total Post:20

Points:140
Posted on    October-14-2013 3:29 AM

 Java Java 
Ratings:


 1 Reply(s)
 712  View(s)
Rate this:

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?



Kate Smith
Kate Smith

Total Post:24

Points:168
Posted on    October-14-2013 4:00 AM

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();
}

Don't want to miss updates? Please click the below button!

Follow MindStick