Method argument of different types

北战南征 提交于 2019-12-11 20:53:55

问题


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?


回答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



回答2:


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



回答3:


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.



来源:https://stackoverflow.com/questions/12436337/method-argument-of-different-types

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!