Search code examples
javareflectionjava-bytecode-asm

Comparing ASM MethodNode parameters


I'm trying to create an method that compares the parameters of 2 methods and give me an percentage of matching parameters, like:

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

Can someone give me a clue how to do this?


Solution

  • Updated with Holger's tips

    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);
    }
    

    Original Code:

    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);
    }
    

    Output for your example methods:

    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