Java Code Examples for com.esotericsoftware.reflectasm.MethodAccess

The following examples show how to use com.esotericsoftware.reflectasm.MethodAccess. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: t-io   Source File: DefaultHttpRequestHandler.java    License: Apache License 2.0 6 votes vote down vote up
private static MethodAccess getMethodAccess(Class<?> clazz) throws Exception {
	MethodAccess ret = CLASS_METHODACCESS_MAP.get(clazz);
	if (ret == null) {
		LockUtils.runWriteOrWaitRead("_tio_http_h_ma_" + clazz.getName(), clazz, () -> {
		    //				@Override
		    //				public void read() {
		    //				}

		    //				@Override
		    //				public void write() {
		    //					MethodAccess ret = CLASS_METHODACCESS_MAP.get(clazz);
		    if (CLASS_METHODACCESS_MAP.get(clazz) == null) {
				//						ret = MethodAccess.get(clazz);
				CLASS_METHODACCESS_MAP.put(clazz, MethodAccess.get(clazz));
			}
			//				}
		});
		ret = CLASS_METHODACCESS_MAP.get(clazz);
	}
	return ret;
}
 
Example 2
Source Project: litchi   Source File: ASMMethod.java    License: Apache License 2.0 5 votes vote down vote up
public static ASMMethod valueOf(Method method, Object instance) {
	ASMMethod asmMethod = new ASMMethod();
	asmMethod.javaMethod = method;
	asmMethod.access = MethodAccess.get(instance.getClass());
	asmMethod.index = asmMethod.access.getIndex(method.getName(), method.getParameterTypes());
	asmMethod.instance = instance;

	asmMethod.isVoid = void.class.equals(method.getReturnType());
	return asmMethod;
}
 
Example 3
Source Project: rpcx-java   Source File: Exporter.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 初始化providerInvoker
 */
private Invoker<Object> initProviderInvoker(String key, String className, String methodName, String[] parameterTypeNames, URL url) {
    Invoker<Object> wrapperInvoker;
    Invoker<Object> invoker = new RpcProviderInvoker<>(getBeanFunc);
    Class clazz = ClassUtils.getClassByName(className);
    invoker.setInterface(clazz);

    invoker.setUrl(url);

    //类级别的注解
    Provider typeProvider = invoker.getInterface().getAnnotation(Provider.class);
    setTypeParameters(typeProvider, url.getParameters());
    Set<String> excludeFilters = Arrays.stream(typeProvider.excludeFilters()).collect(Collectors.toSet());

    //兼容性更好些
    Method method = ClassUtils.getMethod(className, methodName, parameterTypeNames);
    invoker.setMethod(method);

    //reflectasm更快些(实际上是把反射生成了直接调用的代码)
    MethodAccess methodAccess = MethodAccess.get(ClassUtils.getClassByName(className));
    invoker.setMethodAccess(methodAccess);

    //方法级别的注解
    Provider methodProvider = method.getAnnotation(Provider.class);

    //方法级别的会覆盖type级别的
    if (null != methodProvider) {
        setMethodParameters(methodProvider, url.getParameters());
    }

    wrapperInvoker = FilterWrapper.ins().buildInvokerChain(invoker, "", Constants.PROVIDER, excludeFilters);

    invokerMap.putIfAbsent(key, wrapperInvoker);
    return wrapperInvoker;
}
 
Example 4
Source Project: rpcx-java   Source File: CommonTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
    public void testReflect2() {
        Bean bean = new Bean();
        MethodAccess access = MethodAccess.get(Bean.class);
        long begin = System.currentTimeMillis();
        for (int i = 0; i < 100000000; i++) {
            String r = (String) access.invoke(bean, "str", "zzy");
//            System.out.println(r);
        }
        System.out.println(System.currentTimeMillis() - begin);
    }
 
Example 5
Source Project: hxy-socket   Source File: CodeHandlerBean.java    License: GNU General Public License v3.0 5 votes vote down vote up
public CodeHandlerBean(Class<?> clazz, MethodAccess method, Integer index, Class<?>[] paramType, Object bean) {
    this.clazz = clazz;
    this.method = method;
    this.index = index;
    this.paramType = paramType;
    this.bean = bean;
}
 
Example 6
Source Project: hxy-socket   Source File: SimpleCodeHandler.java    License: GNU General Public License v3.0 5 votes vote down vote up
private void onMessageText(ChannelHandlerContext ctx, String msg) {
    if (msg.isEmpty() || msg.trim().isEmpty()) {
        return;
    }
    String clientCode = msg.substring(0, msg.indexOf("|"));
    String surplusStr = msg.substring(msg.indexOf("|") + 1);
    String serverCode = surplusStr.substring(0, surplusStr.indexOf("|"));

    CodeHandlerBean codeHandlerBean = CodeHandlerRouteFactory.getCodeHandlerBean(Integer.parseInt(serverCode));
    if (codeHandlerBean == null) {
        logger.warn("serverCode:{} is not exists", serverCode);
        return;
    }

    String contentJsonStr = surplusStr.substring(surplusStr.indexOf("|") + 1);

    Class<?>[] clzs = codeHandlerBean.getParamType();
    Object[] params = new Object[clzs.length];
    for (int i = 0; i < clzs.length; i++) {
        Class parameter = clzs[i];
        if (Channel.class.isAssignableFrom(parameter)) {
            params[i] = ctx.channel();
        } else if (Client.class.isAssignableFrom(parameter)) {
            Attribute<Client> attribute = ctx.channel().attr(AttributeKey.valueOf(Client.CLIENT_ATTRIBUTE_KEY));
            Client client = attribute.get();
            params[i] = client;
        } else if (int.class.isAssignableFrom(parameter) || Integer.class.isAssignableFrom(parameter)) {
            params[i] = Integer.parseInt(clientCode);
        } else if (Map.class.isAssignableFrom(parameter)) {
            params[i] = JsonUtil.jsonToMap(contentJsonStr);
        } else {
            params[i] = JsonUtil.json2Object(contentJsonStr, parameter);
        }

    }
    MethodAccess methodAccess = codeHandlerBean.getMethod();
    methodAccess.invoke(codeHandlerBean.getBean(), codeHandlerBean.getIndex(), params);
}
 
Example 7
Source Project: hxy-socket   Source File: SimpleCodeHandler.java    License: GNU General Public License v3.0 5 votes vote down vote up
private void onMessageByte(ChannelHandlerContext ctx, byte[] msg) {
    byte[] idByte = new byte[4];
    System.arraycopy(msg, 0, idByte, 0, 4);

    byte[] uriByte = new byte[4];
    System.arraycopy(msg, 4, uriByte, 0, 4);
    int serverCode = ByteUtil.byteArrayToInt(uriByte);

    CodeHandlerBean codeHandlerBean = CodeHandlerRouteFactory.getCodeHandlerBean(serverCode);
    if (codeHandlerBean == null) {
        logger.warn("serverCode:{} is not exists", serverCode);
        return;
    }

    byte[] messageBody = new byte[msg.length - 8];
    System.arraycopy(msg, 8, messageBody, 0, msg.length - 8);

    Class<?>[] clzs = codeHandlerBean.getParamType();
    Object[] params = new Object[clzs.length];
    for (int i = 0; i < clzs.length; i++) {
        Class parameter = clzs[i];
        if (Channel.class.isAssignableFrom(parameter)) {
            params[i] = ctx.channel();
        } else if (Client.class.isAssignableFrom(parameter)) {
            Attribute<Client> attribute = ctx.channel().attr(AttributeKey.valueOf(Client.CLIENT_ATTRIBUTE_KEY));
            Client client = attribute.get();
            params[i] = client;
        } else if (int.class.isAssignableFrom(parameter) || Integer.class.isAssignableFrom(parameter)) {
            params[i] = serverCode;
        }else {
            params[i] = ProtoUtil.deserializeFromByte(messageBody,parameter);
        }
    }
    MethodAccess methodAccess = codeHandlerBean.getMethod();
    methodAccess.invoke(codeHandlerBean.getBean(), codeHandlerBean.getIndex(), params);
}
 
Example 8
Source Project: TakinRPC   Source File: ReflectAsmInvoker.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Object invoke(RemotingProtocol msg) throws Exception {
    Stopwatch watch = Stopwatch.createStarted();

    String methodName = msg.getMethod();
    Object[] args = msg.getArgs();
    Class<?>[] mParamsType = msg.getmParamsTypes();
    Class<?> implClass = GuiceDI.getInstance(ServiceInfosHolder.class).getImplClass(msg.getDefineClass(), msg.getImplClass());

    if (implClass == null) {
        logger.error(String.format("define:%s impl:%s", msg.getDefineClass(), msg.getImplClass()));
        throw new NoImplClassException(msg.getDefineClass().getName());
    }
    String mkey = String.format("%s_%s", implClass.getSimpleName(), methodName);

    MethodAccess access = methodCache.get(mkey);
    if (access == null) {
        logger.info(String.format("method:%s args:%s", methodName, JSON.toJSONString(mParamsType)));
        access = MethodAccess.get(implClass);
        if (access != null) {
            methodCache.putIfAbsent(mkey, access);
        }
    }

    if (access == null) {
        throw new NoImplMethodException(implClass.getName(), methodName);
    }

    Object target = GuiceDI.getInstance(ServiceInfosHolder.class).getOjbectFromClass(implClass.getName());

    Object retval = null;
    //此步反射 非常耗时 
    retval = access.invoke(target, methodName, args);
    if (logger.isDebugEnabled())
        logger.debug(String.format("jdk invoke use:%s", watch.toString()));
    return retval;
}
 
Example 9
Source Project: actframework   Source File: ImplicitVariableProvider.java    License: Apache License 2.0 5 votes vote down vote up
protected ReflectedActionViewVarDef(Meta meta, Class<?> cls, Method method, App app) {
    this.cls = cls;
    this.method = method;
    if (!meta.isStatic) {
        methodAccess = MethodAccess.get(cls);
        methodIndex = methodAccess.getIndex(method.getName(), method.getParameterTypes());
    }
    initLoaders(app);
}
 
Example 10
Source Project: actframework   Source File: ReflectedJobInvoker.java    License: Apache License 2.0 5 votes vote down vote up
private synchronized void init() {
    if (null != jobClass) {
        return;
    }
    disabled = false;
    jobClass = app.classForName(classInfo.className());
    disabled = disabled || !Env.matches(jobClass);
    method = methodInfo.method();
    disabled = disabled || !Env.matches(method);
    if (disabled) {
        return;
    }
    isStatic = methodInfo.isStatic();
    if (!isStatic) {
        singleton = ReflectedInvokerHelper.tryGetSingleton(jobClass, app);
    }
    ParamValueLoaderManager paramValueLoaderManager = app.service(ParamValueLoaderManager.class);
    if (null != paramValueLoaderManager) {
        paramValueLoaderService = paramValueLoaderManager.get(JobContext.class);
    } else {
        // this job is scheduled to run before ParamValueLoaderManager initialized
    }

    if (!Modifier.isStatic(method.getModifiers())) {
        Class[] paramTypes = paramTypes();
        //constructorAccess = ConstructorAccess.get(controllerClass);
        methodAccess = MethodAccess.get(jobClass);
        methodIndex = methodAccess.getIndex(methodInfo.name(), paramTypes);
    } else {
        method.setAccessible(true);
    }
}
 
Example 11
Source Project: MyTown2   Source File: ASMCallerMethod.java    License: The Unlicense 5 votes vote down vote up
@Override
public void setClass(Class<?> clazz) {
    super.setClass(clazz);

    // Setup ReflectASM stuff
    try {
        access = MethodAccess.get(clazz);
        index = access.getIndex(name);
    } catch (Exception ex) {
        MyTown.instance.LOG.debug(name + " - Falling back to reflection based method caller", ex);
        index = -1;
    }
}
 
Example 12
public MethodAccessBenchmark () throws Exception {
	int count = 100000;
	Object[] dontCompileMeAway = new Object[count];
	Object[] args = new Object[0];

	MethodAccess access = MethodAccess.get(SomeClass.class);
	SomeClass someObject = new SomeClass();
	int index = access.getIndex("getName");

	Method method = SomeClass.class.getMethod("getName");
	// method.setAccessible(true); // Improves reflection a bit.

	for (int i = 0; i < 100; i++) {
		for (int ii = 0; ii < count; ii++)
			dontCompileMeAway[ii] = access.invoke(someObject, index, args);
		for (int ii = 0; ii < count; ii++)
			dontCompileMeAway[ii] = method.invoke(someObject, args);
	}
	warmup = false;

	for (int i = 0; i < 100; i++) {
		start();
		for (int ii = 0; ii < count; ii++)
			dontCompileMeAway[ii] = access.invoke(someObject, index, args);
		end("MethodAccess");
	}
	for (int i = 0; i < 100; i++) {
		start();
		for (int ii = 0; ii < count; ii++)
			dontCompileMeAway[ii] = method.invoke(someObject, args);
		end("Reflection");
	}

	chart("Method Call");
}
 
Example 13
Source Project: craft-atom   Source File: DefaultRpcServerInvoker.java    License: MIT License 5 votes vote down vote up
@Override
public RpcMessage invoke(RpcMessage req) throws RpcException {
	String     rpcId        = req.getBody().getRpcId();
	Class<?>   rpcInterface = req.getBody().getRpcInterface();
	RpcMethod  rpcMethod    = req.getBody().getRpcMethod();
	Class<?>[] paramTypes   = rpcMethod.getParameterTypes();
	Object[]   params       = rpcMethod.getParameters();
	String     methodName   = rpcMethod.getName();
	
	RpcApi api = registry.lookup(new DefaultRpcApi(rpcId, rpcInterface, rpcMethod));
	if (api == null) { throw new RpcException(RpcException.SERVER_ERROR, "No exported api mapping"); } 
	Object rpcObject = api.getRpcObject();
	
	
	try {
		// Set rpc context
		RpcContext ctx = RpcContext.getContext();
		ctx.setClientAddress(req.getClientAddress());
		ctx.setServerAddress(req.getServerAddress());
		ctx.setAttachments(req.getAttachments());
		LOG.debug("[CRAFT-ATOM-RPC] Rpc server invoker is invoking, |rpcContext={}|", ctx);
		
		// Reflect invoke
		MethodAccess ma = MethodAccess.get(rpcInterface);
		int methodIndex = ma.getIndex(methodName, paramTypes);
		Object returnObject = ma.invoke(rpcObject, methodIndex, params);
		return RpcMessages.newRsponseRpcMessage(req.getId(), returnObject);
	} catch (Exception e) {
		LOG.warn("[CRAFT-ATOM-RPC] Rpc server invoker error", e);
		if (isDeclaredException(e, rpcInterface, methodName, paramTypes)) {
			return RpcMessages.newRsponseRpcMessage(req.getId(), e);
		} else {
			throw new RpcException(RpcException.SERVER_ERROR, "server error");
		}
	} finally {
		RpcContext.removeContext();
	}
}
 
Example 14
Source Project: rpcx-java   Source File: RpcProviderInvoker.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public void setMethodAccess(MethodAccess methodAccess) {
    this.methodAccess = methodAccess;
}
 
Example 15
Source Project: hxy-socket   Source File: CodeHandlerBean.java    License: GNU General Public License v3.0 4 votes vote down vote up
public MethodAccess getMethod() {
    return method;
}
 
Example 16
Source Project: hxy-socket   Source File: CodeHandlerBean.java    License: GNU General Public License v3.0 4 votes vote down vote up
public void setMethod(MethodAccess method) {
    this.method = method;
}
 
Example 17
Source Project: godaddy-logger   Source File: CacheableAccessors.java    License: MIT License 4 votes vote down vote up
/**
 * Builds the method sorted cache. Sorts the methods alphabetically by name.
 */
private static void buildMethodCache(Class<?> clazz, MethodAccess methodAccess) {

    if(!_methodSortCache.containsKey(clazz)) {
        LogCache[] sortedLogCache = new LogCache[methodAccess.getMethodNames().length];

        String[] sortedMethodNames = Arrays.copyOf(methodAccess.getMethodNames(), sortedLogCache.length);

        Arrays.sort(sortedMethodNames);

        for(int i = 0; i < sortedLogCache.length; i++) {
            sortedLogCache[i] = new LogCache(methodAccess.getIndex(sortedMethodNames[i]),
                                             getMethodLogScope(clazz, sortedMethodNames[i]));
        }

        _methodSortCache.put(clazz, sortedLogCache);
    }

}
 
Example 18
Source Project: godaddy-logger   Source File: CacheableAccessors.java    License: MIT License 4 votes vote down vote up
public static LogCache[] getMethodIndexes(Class<?> clazz, MethodAccess methodAccess) {
    buildMethodCache(clazz, methodAccess);

    return _methodSortCache.get(clazz);
}
 
Example 19
Source Project: actframework   Source File: WebSocketConnectionHandler.java    License: Apache License 2.0 4 votes vote down vote up
public WebSocketConnectionHandler(ActionMethodMetaInfo methodInfo, WebSocketConnectionManager manager) {
    this.connectionManager = $.requireNotNull(manager);
    this.app = manager.app();
    this.initWebSocketConnectionListenerManager();
    if (null == methodInfo) {
        this.isWsHandler = false;
        this.disabled = true;
        return;
    }
    this.handler = $.requireNotNull(methodInfo);
    this.controller = handler.classInfo();

    this.paramLoaderService = app.service(ParamValueLoaderManager.class).get(WebSocketContext.class);
    this.jsonDTOClassManager = app.service(JsonDtoClassManager.class);

    this.handlerClass = app.classForName(controller.className());
    this.disabled = !Env.matches(handlerClass);

    paramTypes = paramTypes(app);

    this.method = $.getMethod(handlerClass, methodInfo.name(), paramTypes);
    E.unexpectedIf(null == method, "Unable to locate handler method: " + methodInfo.name());
    this.isWsHandler = null != this.method.getAnnotation(WsAction.class);
    this.disabled = this.disabled || !Env.matches(method);

    if (!isWsHandler || disabled) {
        return;
    }

    this.isStatic = methodInfo.isStatic();
    if (!this.isStatic) {
        //constructorAccess = ConstructorAccess.get(controllerClass);
        methodAccess = MethodAccess.get(handlerClass);
        methodIndex = methodAccess.getIndex(methodInfo.name(), paramTypes);
        host = Act.getInstance(handlerClass);
    } else {
        method.setAccessible(true);
    }

    paramCount = handler.paramCount();
    paramSpecs = jsonDTOClassManager.beanSpecs(handlerClass, method);
    fieldsAndParamsCount = paramSpecs.size();
    if (fieldsAndParamsCount == 1) {
        singleJsonFieldName = paramSpecs.get(0).name();
    }
    // todo: do we want to allow inject Annotation type into web socket
    // handler method param list?
    ParamValueLoader[] loaders = paramLoaderService.methodParamLoaders(host, method, null);
    if (loaders.length > 0) {
        int realParamCnt = 0;
        for (ParamValueLoader loader : loaders) {
            if (loader instanceof ProvidedValueLoader) {
                continue;
            }
            realParamCnt++;
        }
        isSingleParam = 1 == realParamCnt;
    }
}
 
Example 20
Source Project: actframework   Source File: ReflectedCommandExecutor.java    License: Apache License 2.0 4 votes vote down vote up
public ReflectedCommandExecutor(CommandMethodMetaInfo methodMetaInfo, App app) {
    this.methodMetaInfo = $.requireNotNull(methodMetaInfo);
    this.app = $.NPE(app);
    this.paramTypes = paramTypes();
    this.paramCount = methodMetaInfo.paramCount();
    this.isStatic = methodMetaInfo.isStatic();
    this.commanderClass = app.classForName(methodMetaInfo.classInfo().className());
    try {
        this.method = commanderClass.getMethod(methodMetaInfo.methodName(), paramTypes);
        this.async = null != ReflectedInvokerHelper.getAnnotation(Async.class, method);
        this.reportProgress = ReflectedInvokerHelper.getAnnotation(ReportProgress.class, method);
        FastJsonFilter filterAnno = ReflectedInvokerHelper.getAnnotation(FastJsonFilter.class, method);
        if (null != filterAnno) {
            filters = filterAnno.value();
        }
        FastJsonFeature featureAnno = ReflectedInvokerHelper.getAnnotation(FastJsonFeature.class, method);
        if (null != featureAnno) {
            features = featureAnno.value();
        }
        FastJsonPropertyNamingStrategy propertyNamingStrategyAnno = ReflectedInvokerHelper.getAnnotation(FastJsonPropertyNamingStrategy.class, method);
        if (null != propertyNamingStrategyAnno) {
            propertyNamingStrategy = propertyNamingStrategyAnno.value();
        }
    } catch (NoSuchMethodException e) {
        throw E.unexpected(e);
    }
    if (!methodMetaInfo.isStatic()) {
        methodAccess = MethodAccess.get(commanderClass);
        commandIndex = methodAccess.getIndex(methodMetaInfo.methodName(), paramTypes);
    } else {
        method.setAccessible(true);
    }
    DateFormatPattern dfp = ReflectedInvokerHelper.getAnnotation(DateFormatPattern.class, method);
    if (null != dfp) {
        this.dateFormatPattern = dfp.value();
    } else {
        Pattern pattern = ReflectedInvokerHelper.getAnnotation(Pattern.class, method);
        if (null != pattern) {
            this.dateFormatPattern = pattern.value();
        }
    }
    this.paramLoaderService = app.service(ParamValueLoaderManager.class).get(CliContext.class);
    this.enableCircularReferenceDetect = hasAnnotation(EnableCircularReferenceDetect.class);
    this.buildParsingContext();
}
 
Example 21
Source Project: godaddy-logger   Source File: LoggerMessageBuilder.java    License: MIT License 3 votes vote down vote up
private boolean canLogMethod(LogCache logCache, MethodAccess methodAccess) {
    boolean logScopeSkip = Scope.SKIP == logCache.getLogScope();

    boolean returnTypeNotVoid = methodAccess.getReturnTypes()[logCache.getIndex()] != void.class;

    boolean methodHasNoParameters = methodAccess.getParameterTypes()[logCache.getIndex()].length == 0;

    boolean methodStartsWithDefinedPrefix = trimMethodOfPrefix(methodAccess.getMethodNames()[logCache.getIndex()]) != null;

    return !logScopeSkip && returnTypeNotVoid && methodHasNoParameters && methodStartsWithDefinedPrefix;
}
 
Example 22
Source Project: rpcx-java   Source File: Invoker.java    License: Apache License 2.0 2 votes vote down vote up
default void setMethodAccess(MethodAccess methodAccess){

    }