【发布时间】:2014-11-15 08:50:34
【问题描述】:
要提供一些关于我正在尝试做的事情的背景,请参考我之前的问题:
Run a java method by passing class name and method name as parameter
所以基本上我是在尝试调用一个方法并测试它的返回值。我将从 xml 或数据库中读取以下参数:方法类、名称、参数和返回值。 然后我将执行该方法并比较输出。
代码现在看起来像这样:
public static void main(String[] args) throws IOException {
runTheMethod("CarBean","getColor","java.lang.String","Red");
}
public static void runTheMethod(String className, String methodName, String expectedReturnType, Object expectedReturnValue){
try {
Object classObj = Class.forName(className).newInstance();
Method method = classObj.getClass().getMethod(methodName);
Object returnVal = method.invoke(classObj);
if(expectedReturnValue.getClass().getName().equals(expectedReturnType)){
// This is the problem portion
System.out.println("Test passed : " + expectedReturnValue.equals(returnVal));
}else{
System.out.println("Expected return object type does not match actual return object type");
}
} catch (InstantiationException | IllegalAccessException
| ClassNotFoundException | NoSuchMethodException | SecurityException | IllegalArgumentException | InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Carbean 是用户定义的 pojo :
public class CarBean {
private String brand;
private String color = "Red";
public CarBean (){
}
public CarBean (String brand, String color){
this.brand= brand;
this.color= color;
}
/**
* @return the brand
*/
public String getBrand() {
return brand;
}
/**
* @param the brand to set
*/
public void setBrand(String brand) {
this.brand= brand;
}
/**
* @return the color
*/
public String getColor() {
return color;
}
/**
* @param the color to set
*/
public void setColor(String color) {
this.color= color;
}
@Override
public boolean equals(Object o){
if(o == null)
return false;
if(!(o instanceof CarBean))
return false;
CarBean other = (CarBean) o;
if(this.brand!=null && this.color!=null){
if(this.brand.equals(other.brand) && this.color.equals(other.color))
return true;
else
return false;
}else{
return false;
}
}
@Override
public int hashCode() {
int hash = 17;
hash = 31 * hash + this.brand.hashCode();
hash = 31 * hash + this.color.hashCode();
return hash;
}
}
现在这适用于当前代码 - 返回类型是 String,我可以使用 equals 进行比较。 但是,如果该方法返回 BigDecimal 或 List 怎么办?有没有一种通用的方法可以比较多种对象类型?
我假设对于用户定义的 java beans (pojo),我可以覆盖 equals() 和 hashcode() 来比较它。详情参考我的博客: http://javareferencegv.blogspot.com/2014/10/overriding-equals-and-hashcode-for-pojo.html
任何进一步的建议表示赞赏。
【问题讨论】:
-
是的,您可以使用
equals。我想我真的不明白问题是什么。尽管由于空实例字段处理不当,您在CarBean中对equals和hashCode的实现可以说是不正确的。 -
@Radiodef 看到返回类型可以是任何东西。它可能不会一直覆盖等于。另外,您认为处理空字段有什么问题?
-
我基本上是在尝试制作一个通用代码。它将执行一个方法并将返回值与预期值进行比较。问题是,我将为每个方法运行相同的代码,并且返回类型会有所不同。所以我正在尝试制作一个可以比较任何返回类型的代码
标签: java