gpt4 book ai didi

java - 模拟 isAssignableFrom()

转载 作者:行者123 更新时间:2023-12-02 11:01:32 27 4
gpt4 key购买 nike

我有两个 java 类,如下所示,

public class Class1{
private Object actionObject;
public Object getActionObject() {
return actionObject;
}
public void setActionObject(Object actionObject) {
this.actionObject = actionObject;
}
}

二等

 public class Class2 {
private Long id;
private int idver;
private int valueDate;
}

有如下两条语句,

Class1 deserializedValue = (Class1) event.getDeserializedValue();

Class2.class.isAssignableFrom(deserializedValue.getActionObject().getClass());

我想模拟第二个语句

Class2.class.isAssignableFrom(deserializedValue.getActionObject().getClass());

我该怎么做?

最佳答案

出于测试目的,您可以使用策略模式。您只需要一个具有两种不同实现的接口(interface)或抽象类。其中之一是模拟实现,如下所示:

public interface EventStrategy {

// More methods...

boolean isAssignableFrom(final Object object);

}

public class MyEvent implements EventStrategy {

public boolean isAssignableFrom(final Object object) {
return Class2.class.isAssignableFrom(object.getClass());
}

}

public class MockEvent implements EventStrategy {

public boolean isAssignableFrom(final Object object) {
return true;
}

}

关于java - 模拟 isAssignableFrom(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51298307/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com