比较ASM MethodNode参数

时间:2017-01-14 13:10:42

标签: java reflection java-bytecode-asm

我试图创建一个方法来比较2种方法的参数,并给出一定比例的匹配参数,例如:

Method1(int i, boolean b, char c)    
Method2(boolean b, int i)   
Method3(char c)    
Method4(double d)


Method1 and Method2 = 66% -> 2 matching parameters    
Method1 and Method3 = 33% -> 1 matching parameter
Method1 and Method4 = 0%  -> 0 matching parameters

有人能告诉我怎么做这个吗?

1 个答案:

答案 0 :(得分:3)

更新了Holger的提示

private static float compare(MethodNode mn1, MethodNode mn2) {
    Type[] typeArgs1 = Type.getArgumentTypes(mn1.desc);
    Type[] typeArgs2 = Type.getArgumentTypes(mn2.desc);
    int max = Math.max(typeArgs1.length, typeArgs2.length);
    if (max == 0)
        return 1f;
    int matches = 0;
    List<Type> types = Arrays.asList(typeArgs1);
    for (Type arg : typeArgs2)
        if (types.contains(arg))
            matches++;
    return ((float) matches / max);
}

原始代码:

private static float compare(MethodNode mn1, MethodNode mn2) {
    Type t1 = Type.getMethodType(mn1.desc);
    Type t2 = Type.getMethodType(mn2.desc);
    Type[] targs1 = t1.getArgumentTypes();
    Type[] targs2 = t2.getArgumentTypes();
    int max = Math.max(targs1.length, targs2.length);
    int matches = 0;
    if (max == 0) 
        return 1f;
    List<String> types1 = new ArrayList<String>();
    for (Type t : targs1) 
        types1.add(t.getDescriptor());
    for (Type t : targs2) 
        if (types1.contains(t.getDescriptor())) 
            matches++;  
    return (1F * matches / max);
}

示例方法的输出:

0,1  0.0
0,2  0.0
0,3  0.0
0,4  0.0
1,2  0.6666667
1,3  0.33333334
1,4  0.0
2,3  0.0
2,4  0.0
3,4  0.0