在equals方法上使用isAssignableFrom时覆盖hashCode

时间:2016-10-22 21:15:02

标签: java caching hashmap equals hashcode

我需要找到一种方法来缓存方法(java.lang.reflect.Method),这样每当我用类(Class)methodName(String)和参数调用一个函数时( T[])该函数将返回缓存的方法(如果存在)或找到方法,将其添加到缓存并返回。

我想使用HashMap进行缓存,所以我可以在O(1)中找到该方法,但问题是我在覆盖equals方法时需要使用isAssignableFrom

public class A1 extends AParent {}

public class A2 extends AParent {}

public class AParent {}

public class Temp{
    public void testFunc(AParent a){}
}

这是我用于HashMap中键的类:

import java.util.Arrays;

class MethodAbs{
Class c;
String methodName;
Class<?>[] argsTypes;

public MethodAbs(Class c, String methodName, Class<?>[] argsTypes){
    this.c = c;
    this.methodName = methodName;
    this.argsTypes = argsTypes;
}

@Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;

    MethodAbs methodAbs = (MethodAbs) o;

    if (c != null ? !c.equals(methodAbs.c) : methodAbs.c != null) return false;
    if (methodName != null ? !methodName.equals(methodAbs.methodName) : methodAbs.methodName != null)
        return false;
    return isArgsTypesEq(argsTypes, methodAbs.argsTypes);

}

//a method is equals to the one cached if the arguments types
// can be cast to the ones that are saved on the map,
// i.e the ones on the method declaration 

private boolean isArgsTypesEq(Class<?>[] at1, Class<?>[] at2){
    boolean res = at1.length == at2.length;
    for(int i = 0; i<at1.length && res; i++){
        if(!at1[i].isAssignableFrom(at2[i])) res = false;
    }
    return res;
}


//default implementation (not working properly!)

@Override
public int hashCode() {
    int result = c != null ? c.hashCode() : 0;
    result = 31 * result + (methodName != null ? methodName.hashCode() : 0);
    result = 31 * result + Arrays.hashCode(argsTypes);
    return result;
}


}

我用于缓存的类

class Run{

public Map<MethodAbs, Method> map = new HashMap<>();

public<T> Method myFunc(Class c, String methodName, T[] args){
    MethodAbs ma = new MethodAbs(c, methodName, getTypes(args));
    if(map.containsKey(ma)){
        return map.get(ma);
    }
    else{
        for(Method method: c.getMethods()){
            MethodAbs currMethodAbs = new MethodAbs(c, method.getName(), method.getParameterTypes());
            if(!map.containsKey(currMethodAbs))
                map.put(currMethodAbs, method);
            if(currMethodAbs.equals(ma)) break;
        }
    }
    return map.get(ma);
}

private<T> Class<?>[] getTypes(T[] args) {
    Class<?>[] types = new Class<?>[args.length];
    for(int i = 0; i< args.length; i++){
        types[i] = args[i].getClass();
    }
    return types;
}
}

主要:

 public static void main(String[] args){
    Run r = new Run();
    Object [] arr = new Object[1];
    arr[0] = new A1();
    r.myFunc(Temp.class, "testFunc", arr);
    arr[0] = new A2();
    r.myFunc(Temp.class, "testFunc", arr);

}

在第一次调用r.myFunc之后的上述场景中,地图如下所示:

MethodAbs(Temp.class, "testFunc", [AParent.class]) 

第二次map.containsKey将返回false(因为AParent.hashCode!= A2.hashCode),但它们是equals

  • 示例中显示的层次结构不一定如此(例如A2可以是AParent的孙子)

我知道我可以使用类和方法名称作为键,值将是一个方法列表,我需要迭代并与equals进行比较,但我试图找到更好的方法。 ..

1 个答案:

答案 0 :(得分:0)

不幸的是,由于至少有两个原因,你的equals方法基本上被打破了。

  1. 它不是对称的,请参阅以下代码段:

    public static void main(String... args) {
        MethodAbs methodValueOfObject = new MethodAbs(String.class, "valueOf", new Class<?>[] { Object.class });
        MethodAbs methodValueOfCharArrays = new MethodAbs(String.class, "valueOf", new Class<?>[] { char[].class });
        System.out.println(methodValueOfObject.equals(methodValueOfCharArrays)); // prints "true"
        System.out.println(methodValueOfCharArrays.equals(methodValueOfObject)); // prints "false"
    }
    
  2. 它等同于您可能并不意味着被认为是平等的方法。要想象您的Temp课程有两个testFunc方法,public void testFunc(A1 a)public void testFunc(A2 a)。相应的MethodAbs对象不应该相等,但根据您的实现,它们确实是。

  3. 我认为最适合您的解决方案就是完全摆脱缓存。只需使用

    public Method getMethod(Class<?> c, String methodName, Class<?>... paramClasses) {
        try {
            return c.getDeclaredMethod(methodName, paramClasses);
        } catch (NoSuchMethodException | SecurityException e) {
            // Your exception handling goes here
            return null;
        }
    }
    

    Class个对象已经被类加载器缓存,因此性能损失可以忽略不计。

相关问题