All Downloads are FREE. Search and download functionalities are using the official Maven repository.

shz.AsmHelp Maven / Gradle / Ivy

package shz;

import jdk.internal.org.objectweb.asm.*;
import shz.cache.MapCache;
import shz.constant.ArrayConstant;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.Objects;

public final class AsmHelp {
    private AsmHelp() {
        throw new IllegalStateException();
    }

    private static final MapCache METHOD_PARAMETER_NAMES_CACHE = new MapCache<>(128);

    public static String[] getParameterNames(Method method) {
        Objects.requireNonNull(method);
        String[] result = METHOD_PARAMETER_NAMES_CACHE.get(method);
        if (result != null) return result;

        Class[] pTypes = method.getParameterTypes();
        if (pTypes.length == 0) {
            METHOD_PARAMETER_NAMES_CACHE.put(method, ArrayConstant.EMPTY_STRING_ARRAY);
            return ArrayConstant.EMPTY_STRING_ARRAY;
        }

        Type[] types = Arrays.stream(pTypes).map(Type::getType).toArray(Type[]::new);
        String[] pNames = new String[pTypes.length];
        String cName = method.getDeclaringClass().getName();
        cName = cName.substring(cName.lastIndexOf(".") + 1) + ".class";

        InputStream is = method.getDeclaringClass().getResourceAsStream(cName);

        try {
            ClassReader classReader = new ClassReader(is);
            classReader.accept(new ClassVisitor(Opcodes.ASM4) {
                @Override
                public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {
                    Type[] aTypes = Type.getArgumentTypes(desc);
                    if (method.getName().equals(name) && Arrays.equals(aTypes, types))
                        return new MethodVisitor(Opcodes.ASM4) {
                            @Override
                            public void visitLocalVariable(String name, String desc, String signature, Label start, Label end, int index) {
                                if (index < pNames.length && Modifier.isStatic(method.getModifiers()))
                                    pNames[index] = name;
                                else if (index <= pNames.length && index > 0) pNames[index - 1] = name;
                            }
                        };
                    return null;
                }
            }, 0);
        } catch (IOException e) {
            throw PRException.of(e);
        }

        METHOD_PARAMETER_NAMES_CACHE.put(method, pNames);
        return pNames;
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy