com.esotericsoftware.reflectasm.MethodAccess Java Examples
The following examples show how to use
com.esotericsoftware.reflectasm.MethodAccess.
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 File: DefaultHttpRequestHandler.java From t-io with Apache License 2.0 | 6 votes |
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 File: DefaultRpcServerInvoker.java From craft-atom with MIT License | 5 votes |
@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 #3
Source File: ASMMethod.java From litchi with Apache License 2.0 | 5 votes |
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 #4
Source File: MethodAccessBenchmark.java From reflectasm with BSD 3-Clause "New" or "Revised" License | 5 votes |
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 #5
Source File: ASMCallerMethod.java From MyTown2 with The Unlicense | 5 votes |
@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 #6
Source File: ReflectedJobInvoker.java From actframework with Apache License 2.0 | 5 votes |
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 #7
Source File: ImplicitVariableProvider.java From actframework with Apache License 2.0 | 5 votes |
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 #8
Source File: ReflectAsmInvoker.java From TakinRPC with Apache License 2.0 | 5 votes |
@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 File: SimpleCodeHandler.java From hxy-socket with GNU General Public License v3.0 | 5 votes |
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 #10
Source File: SimpleCodeHandler.java From hxy-socket with GNU General Public License v3.0 | 5 votes |
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 #11
Source File: CodeHandlerBean.java From hxy-socket with GNU General Public License v3.0 | 5 votes |
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 #12
Source File: CommonTest.java From rpcx-java with Apache License 2.0 | 5 votes |
@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 #13
Source File: Exporter.java From rpcx-java with Apache License 2.0 | 5 votes |
/** * 初始化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 #14
Source File: CodeHandlerBean.java From hxy-socket with GNU General Public License v3.0 | 4 votes |
public void setMethod(MethodAccess method) { this.method = method; }
Example #15
Source File: CodeHandlerBean.java From hxy-socket with GNU General Public License v3.0 | 4 votes |
public MethodAccess getMethod() { return method; }
Example #16
Source File: CacheableAccessors.java From godaddy-logger with MIT License | 4 votes |
/** * 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 #17
Source File: CacheableAccessors.java From godaddy-logger with MIT License | 4 votes |
public static LogCache[] getMethodIndexes(Class<?> clazz, MethodAccess methodAccess) { buildMethodCache(clazz, methodAccess); return _methodSortCache.get(clazz); }
Example #18
Source File: WebSocketConnectionHandler.java From actframework with Apache License 2.0 | 4 votes |
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 #19
Source File: ReflectedCommandExecutor.java From actframework with Apache License 2.0 | 4 votes |
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 #20
Source File: RpcProviderInvoker.java From rpcx-java with Apache License 2.0 | 4 votes |
@Override public void setMethodAccess(MethodAccess methodAccess) { this.methodAccess = methodAccess; }
Example #21
Source File: LoggerMessageBuilder.java From godaddy-logger with MIT License | 3 votes |
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 File: Invoker.java From rpcx-java with Apache License 2.0 | 2 votes |
default void setMethodAccess(MethodAccess methodAccess){ }