生成缓存Key

@param className 类名称
@param method    方法名称
@param arguments 参数
@return CacheKey 缓存Key
976642
public static String getDefaultCacheKey(String className, String method, Object[] arguments) {
        StringBuilder sb = new StringBuilder();
        sb.append(getDefaultCacheKeyPrefix(className, method, arguments));
        if (null != arguments && arguments.length > 0) {
            sb.append(getUniqueHashStr(arguments));
        }
        return sb.toString();
    }
1154702
public static Method getMethod(Class<?> clazz, String methodName, Class<?>... parameterTypes) {
        Assert.notNull(clazz, "类型不能为空");
        Assert.notNull(methodName, "方法名不能为空");

        return METHOD_CACHE.compute(new MethodKey(methodName, clazz, parameterTypes), (k, v) -> {
            if (v == null) {
                try {
                    return allowAccess(clazz.getDeclaredMethod(methodName, parameterTypes));
                } catch (NoSuchMethodException e) {
                    log.error(
                        StringUtils.format("类[{0}]中不存在方法名为[{1}]、方法列表为[{2}]的方法", clazz, methodName,
                            parameterTypes == null ? "null" : Arrays.toString(parameterTypes)));
                    throw new ReflectException(
                        StringUtils.format("类[{0}]中不存在方法名为[{1}]、方法列表为[{2}]的方法", clazz, methodName,
                            parameterTypes == null ? "null" : Arrays.toString(parameterTypes)),
                        e);
                }
            } else {
                return v;
            }
        });
    }
1210845
public static Map<Integer, List<AnnotationInstance>> createParameterAnnotationMap(final MethodInfo method) {
        final Map<Integer, List<AnnotationInstance>> result = new HashMap<>();
        for (AnnotationInstance ai : method.annotations()) {
            final AnnotationTarget at = ai.target();
            if (at.kind() == AnnotationTarget.Kind.METHOD_PARAMETER) {
                final MethodParameterInfo mp = at.asMethodParameter();
                final int pos = (int) mp.position();
                List<AnnotationInstance> list = result.get(pos);
                if (list == null) {
                    list = new ArrayList<>();
                    result.put(pos, list);
                }
                list.add(ai);
            }
        }
        return result;
    }
1328075
public static XMethod createXMethod(String className, Method method) {
        String methodName = method.getName();
        String methodSig = method.getSignature();
        int accessFlags = method.getAccessFlags();

        return createXMethod(className, methodName, methodSig, accessFlags);
    }
858483
@SuppressWarnings("unchecked")
	private String genarateQueryCacheKey(String keyPattern,Object param){
		if(param instanceof Map){
			Map<String, Object> map = (Map<String, Object>) param;
			Object[] args = new String[map.size()/2];
			if(map.containsKey(STR_COLLECTION) || map.containsKey(STR_LIST)){
				args[0] = CacheKeyUtils.toString(map.containsKey(STR_COLLECTION) ? map.get(STR_COLLECTION) : map.get(STR_LIST));
			}else{				
				for (int i = 0; i < args.length; i++) {
					args[i] = CacheKeyUtils.toString(map.get(STR_PARAM + (i+1)));
				}
			}
			return String.format(keyPattern, args);
		}else if(param instanceof BaseEntity){
			Serializable id = ((BaseEntity)param).getId();
			if(id != null && !"0".equals(id.toString())){				
				return String.format(keyPattern, ((BaseEntity)param).getId());
			}else{
				return String.format(keyPattern, CacheKeyUtils.toString(param));
			}
		}else if(param instanceof Object[]){
			return String.format(keyPattern, (Object[])param);
		}else{
			return param == null ? keyPattern : String.format(keyPattern, CacheKeyUtils.toString(param));
		}
	}
66325
public Method getJavaMethod(Class<?> clazz, String methodName) {
        String className = clazz.getName();
        Method[] methods = allMethodCache.get(className);
        if (methods == null) {
            initJavaClassCache(clazz);// 分析一次clazz,这时会跟新allMethodCache
            methods = allMethodCache.get(className);
        }
        if (methods == null) {
            return null;
        }

        for (Method method : methods) {
            if (methodName.equals(method.getName())) {
                return method;
            }
        }
        return null;
    }
916324
def get_cache_key(datatable_class, view=None, user=None, **kwargs):
    

    datatable_name = datatable_class.__name__
    if datatable_name.endswith('_Synthesized'):
        datatable_name = datatable_name[:-12]
    datatable_id = '%s.%s' % (datatable_class.__module__, datatable_name)
    if CACHE_KEY_HASH:
        datatable_id = _hash_key_component(datatable_id)

    cache_key = 'datatable_%s' % (datatable_id,)

    if view:
        if not inspect.isclass(view):
            # Reduce view to its class
            view = view.__class__

        view_id = '%s.%s' % (view.__module__, view.__name__)
        if CACHE_KEY_HASH:
            view_id = _hash_key_component(view_id)
        cache_key += '__view_%s' % (view_id,)

    if user and user.is_authenticated():
        cache_key += '__user_%s' % (user.pk,)

    # All other kwargs are used directly to create a hashed suffix
    # Order the kwargs by key name, then convert them to their repr() values.
    items = sorted(kwargs.items(), key=lambda item: item[0])
    values = []
    for k, v in items:
        values.append('%r:%r' % (k, v))

    if values:
        kwargs_id = '__'.join(values)
        kwargs_id = _hash_key_component(kwargs_id)
        cache_key += '__kwargs_%s' % (kwargs_id,)

    log.debug("Cache key derived for %r: %r (from kwargs %r)", datatable_class, cache_key, values)

    return cache_key
46733
public static Method getGetMethod(Class c, String methodName, Class... paras)
	{

		//需要优化
		try
		{

			Method m = c.getMethod(methodName, paras);
			m.setAccessible(true);
			return m;
		}
		catch (SecurityException e)
		{
			return null;
		}
		catch (NoSuchMethodException e)
		{
			return null;
		}
	}
1255534
public static String getSetKey(ExecutableElement method) {
    StringBuilder result = new StringBuilder();
    AnnotationMirror qualifier = getQualifier(method.getAnnotationMirrors());
    if (qualifier != null) {
      qualifierToString(qualifier, result);
    }
    result.append(SET_PREFIX);
    typeToString(method.getReturnType(), result, '$');
    result.append(">");
    return result.toString();
  }
74637
def key(self, *args, **kwargs):
        
        if not args and not kwargs:
            return self.class_path
        try:
            if args and not kwargs:
                return "%s:%s" % (self.class_path, self.hash(args))
            # The line might break if your passed values are un-hashable.  If
            # it does, you need to override this method and implement your own
            # key algorithm.
            return "%s:%s:%s:%s" % (self.class_path,
                                    self.hash(args),
                                    self.hash([k for k in sorted(kwargs)]),
                                    self.hash([kwargs[k] for k in sorted(kwargs)]))
        except TypeError:
            raise RuntimeError(
                "Unable to generate cache key due to unhashable"
                "args or kwargs - you need to implement your own"
                "key generation method to avoid this problem")
464862
private String generateMethodKey(CtMethod method) throws NotFoundException {
        String classQualifiedName = method.getDeclaringClass().getName();
        String methodSimpleName = method.getName();
        List<String> argClassQualifiedNames = getArgClassQualifiedNames(method);
        return TestMethod.generateMethodKey(classQualifiedName, methodSimpleName, argClassQualifiedNames);
    }
711917
public static MethodParameters of(Method method) {

		Assert.notNull(method, "Method must not be null!");

		return CACHE.computeIfAbsent(method, MethodParameters::new);
	}
675749
@Nullable
	@Override
	public String getMapping(Class<?> type, Method method) {

		String key = key(type, method);

		return MAPPINGS.computeIfAbsent(key, __ -> delegate.getMapping(type, method));
	}
635917
def memoize_method(method):
    """"""
    cache = {}

    @functools.wraps(method)
    def wrapper(self, *args, **kwargs):
        """Caching wrapper."""
        key = (args, tuple(sorted(kwargs.items())))
        if key in cache:
            return cache[key]
        else:
            result = method(self, *args, **kwargs)
            cache[key] = result
            return result

    return wrapper
515051
@SuppressWarnings("unchecked")
	private T createInstance(final String className, final Object... arguments) {
		try {
			Class<?> implementation = Class.forName(className, false, classLoader);
			if (service.isAssignableFrom(implementation)) {
				return (T) implementation.getDeclaredConstructor(argumentTypes).newInstance(arguments);
			} else {
				InternalLogger.log(Level.ERROR, "Class '" + className + "' does not implement servcie interface '" + service + "'");
			}
		} catch (ClassNotFoundException ex) {
			InternalLogger.log(Level.ERROR, "Service implementation '" + className + "' not found");
		} catch (NoSuchMethodException ex) {
			InternalLogger.log(Level.ERROR, "Service implementation '" + className + "' has no matching constructor");
		} catch (InstantiationException ex) {
			InternalLogger.log(Level.ERROR, "Service implementation '" + className + "' is not instantiable");
		} catch (IllegalAccessException ex) {
			InternalLogger.log(Level.ERROR, "Constructor of service implementation '" + className + "' is not accessible");
		} catch (IllegalArgumentException ex) {
			InternalLogger.log(Level.ERROR, "Illegal arguments for constructor of service implementation '" + className + "'");
		} catch (InvocationTargetException ex) {
			InternalLogger.log(Level.ERROR, ex.getTargetException(), "Failed creating service implementation '" + className + "'");
		}

		return null;
	}
815303
def method_cache(by='value',method='run'):
    """"""

    def decorate_(func):
        def decorate(*args, **kwargs):
            model = args[0] # Assumed to be self.
            assert hasattr(model,method), "Model must have a '%s' method."%method
            if func.__name__ == method: # Run itself.
                method_args = kwargs
            else: # Any other method.
                method_args = kwargs[method] if method in kwargs else {}
            if not hasattr(model.__class__,'cached_runs'): # If there is no run cache.
                model.__class__.cached_runs = {} # Create the method cache.
            cache = model.__class__.cached_runs
            if by == 'value':
                model_dict = {key:value for key,value in list(model.__dict__.items()) \
                              if key[0]!='_'}
                method_signature = SciUnit.dict_hash({'attrs':model_dict,'args':method_args}) # Hash key.
            elif by == 'instance':
                method_signature = SciUnit.dict_hash({'id':id(model),'args':method_args}) # Hash key.
            else:
                raise ValueError("Cache type must be 'value' or 'instance'")
            if method_signature not in cache:
                print("Method with this signature not found in the cache. Running...")
                f = getattr(model,method)
                f(**method_args)
                cache[method_signature] = (datetime.now(),model.__dict__.copy())
            else:
                print("Method with this signature found in the cache. Restoring...")
                _,attrs = cache[method_signature]
                model.__dict__.update(attrs)
            return func(*args, **kwargs)
        return decorate
    return decorate_
1165333
function create(method, options = {}) {
    options = Object.assign(exports.defaults, options);
    exports.results.set(method, new lru_cache_1.default(options));
    return exports.results.get(method);
}