-2

公共无效测试(对象 obj){

       //Here i have to set the values of the obj using its setter . 
    }

可以使用两个对象作为参数调用测试。EG:test(standalone) 和 test(webapp),其中standalone 和 webapp 是 bean。

public class standalone{
      int version;
   //setter and getter
}

public class Webapp{
     String version;
   //setter and getter
}

此测试方法必须根据参数对象设置值。例如:如果我将独立作为参数传递。独立的 setter 方法 shd 被调用。如何做到这一点?

注意:不使用接口。这个怎么做?谢谢。

4

6 回答 6

1
public static void setVersion(Object obj, int v) throws Exception {
  for (Method m : obj.getClass().getMethods()) {
    final Class<?>[] t = m.getParameterTypes();
    if (m.getName().equals("setVersion") && t.length == 1)
      m.invoke(obj, t[0] == String.class? String.valueOf(v) : v);
      break;
  }
}
于 2012-06-29T11:47:14.107 回答
0

我认为最好在这种情况下使用继承,因为(据我所知)独立和 WebApp 都是应用程序。

因此,您可以定义一个顶级“应用程序”并且 StandaloneApp 和 WebApp 都对其进行扩展,因为可以定义“是一个”关系。

骨架代码:

define class Application
define class StandaloneApp extends Application, implements method setVersion(int)
define class WebApp extends Application, implements method setVersion(int)

define test method, which accepts "Application" obj in the arguments

您也可以应用上面介绍的任何界面解决方案。

于 2012-06-29T11:58:47.980 回答
0

你可以简单地这样做:

interface SetVersion{
    void setVersion(int version);
}
class Standalone implements SetVersion{}
class WebApp implements SetVersion{}
public void test(SetVersion version){
      version.setVersion(1);
    }

或者最简单的方法是使用.instanceOf

if(obj.instanceOf(Standalone)){

}
于 2012-06-29T12:08:26.847 回答
0

以最简单的方式,您可以这样做:

public void test(Object obj) {

    if( obj instanceof Standalone ) {
        ((Standalone)obj).setVersion(1);
    } else if (obj instanceof WebApp ) {
        ((WebApp)obj).setVersion(1);
    }

}

尽量避免使用反射来实现这一点,因为它会使重构任务变得非常困难。将类名与字符串进行比较也是如此。

如果你想要更优雅的东西,你可以这样做:

public class abstract AbstractEnv {
    int version = 0;
    // setters and getters
}

public class Standalone extends AbstractEnv{
}

public class Webapp extends AbstractEnv{
}

使用这种方法,您可以像这样配置它:

public void test(AbstractEnv obj) {

    obj.setVersion(1);

}
于 2012-06-29T11:46:49.167 回答
0

你的两个类都应该实现一个接口,比如VersionSettable. 其中声明了方法setVersion(int version)

public class standalone implements VersionSettable {
      int version;
   //setter and getter
}

public class Webapp implements VersionSettable {
      int version;
   //setter and getter
}

interface VersionSettable {
    setVersion(int version);
}

然后您可以将您的测试方法更改为:

public void test(VersionSettable obj){
   obj.setVersion(17);
}
于 2012-06-29T11:47:53.413 回答
0

您可以让 StandAlone 和 WebApp 都实现一个接口,例如

interface VersionSettable {
    void setVersion(int version);
}

public class Standalone implements VersionSettable{
      int version;
   //setter and getter
}

public class Webapp implements VersionSettable{
      int version;
   //setter and getter
}

public void test(VersionSettable versionSettable){
   versionSettable.setVersion(42);
}
于 2012-06-29T11:51:16.293 回答