使用Java反射查找最匹配的writeMethod

Commons BeanUtils getMatchingAccessibleMethod找到匹配项,但不是最佳匹配项.

考虑这个简单的例子:

public class TestReflection extends TestCase {

  public static class BeanA {
    private DataX data;
    public BeanA setData(DataX x) {
      System.out.println("setData x");
      return this;
    }
    public BeanA setData(DataY y) {
      System.out.println("setData y");
      return this;
    }
  }

  static class DataX {
  }
  static class DataY extends DataX {
  }
  static class DataZ extends DataY {
  }

  public void testPropertyUtils() {
    try {
      BeanA a = new BeanA();
      System.out.println("--- setters:");
      a.setData(new DataX());
      a.setData(new DataY());
      a.setData(new DataZ());
      System.out.println("--- invokeMethod");
      MethodUtils.invokeMethod(a, "setData", new DataZ());
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

(提示:invokeMethod使用getMatchingAccessibleMethod)

上面的代码输出

--- setters:
setData x
setData y
setData y
--- invokeMethod
setData x

最后一行说“setData y”,因为用DataZ对象调用“setData”的最佳匹配应该是接口中具有DataY的那个(就像setData(new DataZ())那样).

有没有办法找到最好的匹配或我必须自己编码?

最佳答案 我很好奇它是如何在MethodUtils.java中工作的,所以我看了看里面.要确定哪种方法应该用作最佳匹配,每种方法都会获得成本.要计算成本,有一个方法(带有一些额外的dbg输出):

/**
 * Gets the number of steps required needed to turn the source class into the 
 * destination class. This represents the number of steps in the object hierarchy 
 * graph.
 * @param srcClass The source class
 * @param destClass The destination class
 * @return The cost of transforming an object
 */
private static float getObjectTransformationCost(Class srcClass, Class destClass) {
    System.out.println("----------- start calculate cost from " + srcClass + " to " + destClass + "------------");

    float cost = 0.0f;
    while (destClass != null && !destClass.equals(srcClass)) {
        System.out.println(srcClass + " and " + destClass + " are " + (destClass.equals(srcClass)? " equal" : " not equal"));
        if (destClass.isInterface() && isAssignmentCompatible(destClass,srcClass)) {
            // slight penalty for interface match. 
            // we still want an exact match to override an interface match, but  
            // an interface match should override anything where we have to get a 
            // superclass.
            cost += 0.25f;
            break;
        }
        cost++;

        destClass = destClass.getSuperclass();
    }

    /*
     * If the destination class is null, we've travelled all the way up to 
     * an Object match. We'll penalize this by adding 1.5 to the cost.
     */
    if (destClass == null) {
        cost += 1.5f;
    }
    System.out.println("COST IS " + cost);


    return cost;
}

所以输出是

--- setters:
setData x
setData y
setData y
--- invokeMethod
----------- start calculate cost from class Lolka$DataZ to class Lolka$DataX------------
class Lolka$DataZ and class Lolka$DataX are  not equal
class Lolka$DataZ and class java.lang.Object are  not equal
COST IS 3.5
----------- start calculate cost from class Lolka$DataZ to class Lolka$DataY------------
class Lolka$DataZ and class Lolka$DataY are  not equal
class Lolka$DataZ and class Lolka$DataX are  not equal
class Lolka$DataZ and class java.lang.Object are  not equal
COST IS 4.5
setData x

因此invokeMethode假定转换DataX只是一个继承级别的表单Object,而DataY是2.所以DataX方法“更便宜”.这就是背后的逻辑.

UPD:
将dest更改为src工作正常,所以如果我使用

private static float getObjectTransformationCost(Class srcClass, Class destClass) {
    float cost = 0.0f;
    while (srcClass != null && !destClass.equals(srcClass)) {
        if (destClass.isInterface() && isAssignmentCompatible(destClass,srcClass)) {
            cost += 0.25f;
            break;
        }
        cost++;

        srcClass = srcClass.getSuperclass();
    }

    if (srcClass == null) {
        cost += 1.5f;
    }

    return cost;
}

输出是

--- setters:
setData x
setData y
setData y
--- invokeMethod
setData y
点赞