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

com.undefinedlabs.scope.jdk.reflection.ReflectionContext Maven / Gradle / Ivy

package com.undefinedlabs.scope.jdk.reflection;

import java.lang.reflect.Method;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

public enum ReflectionContext {
  INSTANCE;

  private static final Map CLASS_MAP = new HashMap<>();
  private static final Map METHOD_MAP = new HashMap<>();

  public Method getScopeMethod(
      final String className, final String methodName, final Class... argsClass) {
    return getScopeMethod(className, ClassLoader.getSystemClassLoader(), methodName, argsClass);
  }

  public Method getScopeMethod(
      final String className,
      final ClassLoader classLoader,
      final String methodName,
      final Class... argsClass) {
    try {
      final String methodHash = calculateMethodHash(className, methodName, argsClass);

      synchronized (METHOD_MAP) {
        Method method = METHOD_MAP.get(methodHash);
        if (method == null) {
          final Class clazz = getScopeClass(className, classLoader);
          method = clazz.getMethod(methodName, argsClass);
          method.setAccessible(true);
          METHOD_MAP.put(methodHash, method);
        }

        return method;
      }
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

  public Class getScopeClass(final String className) {
    return getScopeClass(className, ClassLoader.getSystemClassLoader());
  }

  public Class getScopeClass(final String className, final ClassLoader classLoader) {
    try {
      synchronized (CLASS_MAP) {
        final ClassKey classKey = new ClassKey(className, classLoader);
        Class clazz = CLASS_MAP.get(classKey);
        if (clazz == null) {
          final Class classForName = Class.forName(className, false, classLoader);
          CLASS_MAP.put(classKey, classForName);
          clazz = classForName;
        }

        return clazz;
      }
    } catch (ClassNotFoundException e) {
      throw new RuntimeException(e);
    }
  }

  private String calculateMethodHash(
      final String className, final String methodName, final Class... argsClass)
      throws NoSuchAlgorithmException {
    final StringBuilder stringBuilder = new StringBuilder();
    stringBuilder.append(className).append(methodName);
    for (Class argClass : argsClass) {
      stringBuilder.append(argClass.getName());
    }

    return MessageDigest.getInstance("MD5").digest(stringBuilder.toString().getBytes()).toString();
  }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy