net.sf.cglib.reflect.FastMethod Java Examples

The following examples show how to use net.sf.cglib.reflect.FastMethod. 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: RpcHandler.java    From rpc4j with MIT License 6 votes vote down vote up
private Object handle(RpcRequest request) throws Throwable {
	String className = request.getClassName();
	Object serviceBean = handlerMap.get(className);

	Class<?> serviceClass = serviceBean.getClass();
	String methodName = request.getMethodName();
	Class<?>[] parameterTypes = request.getParameterTypes();
	Object[] parameters = request.getParameters();

	/*
	 * Method method = serviceClass.getMethod(methodName, parameterTypes);
	 * method.setAccessible(true); return method.invoke(serviceBean,
	 * parameters);
	 */

	FastClass serviceFastClass = FastClass.create(serviceClass);
	FastMethod serviceFastMethod = serviceFastClass.getMethod(methodName, parameterTypes);
	return serviceFastMethod.invoke(serviceBean, parameters);
}
 
Example #2
Source File: MethodExpression.java    From PoseidonX with Apache License 2.0 6 votes vote down vote up
private Class< ? > resolveType(IExpression[] exprs)
{
    //获得函数参数类型
    Class< ? >[] paramTypes = new Class[exprs.length];
    for (int i = 0; i < paramTypes.length; i++)
    {
        paramTypes[i] = exprs[i].getType();
    }
    
    //获得相应方法
    Method method = MethodResolver.resolveMethod(declareClass, methodName, paramTypes);
    if (null == method)
    {
        UDFAnnotation annotation = declareClass.getAnnotation(UDFAnnotation.class);
        String functionName = annotation == null ? declareClass.getSimpleName() : annotation.value();
        StreamingRuntimeException exception =
         new StreamingRuntimeException(ErrorCode.FUNCTION_UNSUPPORTED_PARAMETERS, functionName);
        LOG.error(ErrorCode.FUNCTION_UNSUPPORTED_PARAMETERS.getFullMessage(functionName));
        throw exception;
    }
    FastClass declaringClass =
        FastClass.create(Thread.currentThread().getContextClassLoader(), method.getDeclaringClass());
    FastMethod md = declaringClass.getMethod(method);
    return warpDataType(md.getReturnType());
}
 
Example #3
Source File: ProxyInvocation.java    From redant with Apache License 2.0 6 votes vote down vote up
/**
 * 执行方法的调用
 * @param controller 控制器
 * @param method 方法
 * @param methodName 方法名
 * @return 渲染结果
 * @throws Exception 异常
 */
      Object invoke(Object controller, Method method, String methodName) throws Exception {
	if (method == null) {
		throw new NoSuchMethodException("Can not find specified method: " + methodName);
	}

	Class<?> clazz = controller.getClass();
	Class<?>[] parameterTypes = method.getParameterTypes();
	Object[] parameters = null;
	Object result;
	try {
		parameters = getParameters(method,parameterTypes);
		// 使用 CGLib 执行反射调用
		FastClass fastClass = FastClass.create(clazz);
		FastMethod fastMethod = fastClass.getMethod(methodName, parameterTypes);
		// 调用,并得到调用结果
		result = fastMethod.invoke(controller, parameters);

	} catch(InvocationTargetException e){
		String msg = "调用出错,请求类["+controller.getClass().getName()+"],方法名[" + method.getName() + "],参数[" + Arrays.toString(parameters)+"]";
		throw getInvokeException(msg, e);
	}
	return result;
}
 
Example #4
Source File: ReflectPerformanceTest.java    From JavaBase with MIT License 6 votes vote down vote up
@Test
public void testCglib() throws Exception {
  long sum = 0;
  TargetObject targetObject = new TargetObject();

  FastClass testClazz = FastClass.create(TargetObject.class);
  FastMethod method = testClazz.getMethod("setNum", new Class[]{int.class});

  Object[] param = new Object[1];
  time.startCount();
  for (int i = 0; i < LOOP_SIZE; ++i) {
    param[0] = i;
    method.invoke(targetObject, param);
    sum += targetObject.getNum();
  }

  time.endCountOneLine("use cglib ");
  log.info("LOOP_SIZE {} 和是 {} ", LOOP_SIZE, sum);
}
 
Example #5
Source File: ProxyInvocation.java    From bitchat with Apache License 2.0 6 votes vote down vote up
/**
 * 执行方法的调用
 *
 * @param controller 控制器
 * @param method     方法
 * @param methodName 方法名
 * @return 渲染结果
 * @throws Exception 异常
 */
Object invoke(Object controller, Method method, String methodName) throws Exception {
    if (method == null) {
        throw new NoSuchMethodException("Can not find specified method: " + methodName);
    }

    Class<?> clazz = controller.getClass();
    Class<?>[] parameterTypes = method.getParameterTypes();
    Object[] parameters = null;
    Object result;
    try {
        parameters = getParameters(method, parameterTypes);
        // 使用 CGLib 执行反射调用
        FastClass fastClass = FastClass.create(clazz);
        FastMethod fastMethod = fastClass.getMethod(methodName, parameterTypes);
        // 调用,并得到调用结果
        result = fastMethod.invoke(controller, parameters);

    } catch (InvocationTargetException e) {
        String msg = "调用出错,请求类[" + controller.getClass().getName() + "],方法名[" + method.getName() + "],参数[" + Arrays.toString(parameters) + "]";
        throw getInvokeException(msg, e);
    }
    return result;
}
 
Example #6
Source File: ServiceBeanFactory.java    From springtime with Apache License 2.0 5 votes vote down vote up
public void add(String prefix, String serviceName, Object serviceBean) {
	Class<?> serviceClass = serviceBean.getClass();
	FastClass serviceFastClass = FastClass.create(serviceClass);

	Method[] methods = serviceClass.getDeclaredMethods();

	for (Method method : methods) {
		method.setAccessible(true);
		FastMethod fastMethod = serviceFastClass.getMethod(method);
		MethodInvoker methodInvoker = new MethodInvoker(serviceBean, fastMethod);

		methodInvokerMap.put(prefix + "/" + serviceName + "/" + method.getName().toLowerCase(), methodInvoker);
	}
}
 
Example #7
Source File: Dispatcher.java    From api-compiler with Apache License 2.0 5 votes vote down vote up
@Override
public Optional<FastMethod> load(Class<? extends BaseType> type) throws Exception {
  // try to use super type
  Class<?> rawSuperType = type.getSuperclass();
  if (rawSuperType == null || !baseType.isAssignableFrom(rawSuperType)) {
    return Optional.absent();
  }
  @SuppressWarnings("unchecked") // checked at runtime
  Class<? extends BaseType> superType = (Class<? extends BaseType>) rawSuperType;
  return dispatchTable.getUnchecked(superType);
}
 
Example #8
Source File: Dispatcher.java    From api-compiler with Apache License 2.0 5 votes vote down vote up
/**
 * Initializes the dispatcher table. This maps every type
 * to precisely the method which handles it. At lookup time we
 * will incrementally populate the table with additional entries
 * for super-types.
 */
private void initialize(Class<? extends Annotation> marker, Class<?> provider) {
  Class<?> providerSuper = provider.getSuperclass();
  if (providerSuper != null && providerSuper != Object.class) {
    // First get methods from super class. They can be overridden later.
    initialize(marker, providerSuper);
  }
  // Now get methods from this provider.
  FastClass fastProvider = FastClass.create(provider);
  for (Method method : provider.getDeclaredMethods()) {
    Annotation dispatched = method.getAnnotation(marker);
    if (dispatched == null) {
      continue;
    }

    Preconditions.checkState((method.getModifiers() & Modifier.STATIC) == 0,
        "%s must not be static", method);
    Preconditions.checkState(method.getParameterTypes().length == 1,
        "%s must have exactly one parameter", method);
    @SuppressWarnings("unchecked") // checked at runtime
    Class<? extends BaseType> dispatchedOn =
        (Class<? extends BaseType>) method.getParameterTypes()[0];
    Preconditions.checkState(baseType.isAssignableFrom(dispatchedOn),
        "%s parameter must be assignable to %s", method, baseType);

    Optional<FastMethod> oldMethod = dispatchTable.getIfPresent(dispatchedOn);
    if (oldMethod != null && oldMethod.get().getDeclaringClass() == provider) {
      throw new IllegalStateException(String.format(
          "%s clashes with already configured %s from same class %s",
          method, oldMethod.get().getJavaMethod(), provider));
    }
    dispatchTable.put(dispatchedOn, Optional.of(fastProvider.getMethod(method)));
  }
}
 
Example #9
Source File: GenericVisitor.java    From api-compiler with Apache License 2.0 5 votes vote down vote up
private boolean dispatchBefore(Dispatcher<BaseType> dispatcher, BaseType instance) {
  FastMethod method = getMethod(dispatcher, instance);
  if (method == null) {
    return true; // non-presence of before method means continue execution
  }
  try {
    Object result = method.invoke(this, new Object[]{ instance });
    if (method.getReturnType().equals(Boolean.TYPE)) {
      return Boolean.class.cast(result); // method determines whether to continue
    }
    return true;
  } catch (InvocationTargetException e) {
    throw Throwables.propagate(e.getCause());
  }
}
 
Example #10
Source File: GenericVisitor.java    From api-compiler with Apache License 2.0 5 votes vote down vote up
private boolean dispatch(Dispatcher<BaseType> dispatcher, BaseType instance) {
  FastMethod method = getMethod(dispatcher, instance);
  if (method == null) {
    return false;
  }
  try {
    method.invoke(this, new Object[]{ instance });
    return true;
  } catch (InvocationTargetException e) {
    throw Throwables.propagate(e.getCause());
  }
}
 
Example #11
Source File: CGlibInvoker.java    From TakinRPC with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("rawtypes")
@Override
public Object invoke(RemotingProtocol msg) throws Exception {
    Stopwatch watch = Stopwatch.createStarted();
    Object[] args = msg.getArgs();
    Class<?> implClass = GuiceDI.getInstance(ServiceInfosHolder.class).getImplClass(msg.getDefineClass(), msg.getImplClass());
    if (implClass == null) {
        throw new NoImplClassException(msg.getDefineClass().getName());
    }

    logger.info(implClass.getName());

    //        Tcc tcc = GuiceDI.getInstance(TccProvider.class).getCompensable(msg.getDefineClass());
    //        logger.info(JSON.toJSONString(tcc));
    try {
        FastClass fastClazz = FastClass.create(implClass);
        // fast class反射调用  
        String mkey = String.format("%s_%s", implClass.getSimpleName(), msg.getMethod());
        Tuple<Object, FastMethod> classmethod = map.get(mkey);
        if (classmethod == null) {
            Object target = fastClazz.newInstance();
            FastMethod method = fastClazz.getMethod(msg.getMethod(), msg.getmParamsTypes());
            if (method != null) {
                map.put(mkey, new Tuple<Object, FastMethod>(target, method));
            }
        }
        Object obj = classmethod.value.invoke(classmethod.key, args);

        logger.info(String.format("cglib invoke use:%s", watch.toString()));
        return obj;
    } catch (Exception e) {
        throw e;
    }
}
 
Example #12
Source File: JdbcFastMethodInvocation.java    From j360-tools with Apache License 2.0 5 votes vote down vote up
public static FastMethod build(final Class<?> clz, Method method) {
    FastClass fastClz = fastClassMap.get(clz);
    if (Objects.isNull(fastClz)) {
        fastClz = FastClass.create(clz);
        fastClassMap.putIfAbsent(clz, fastClz);
    }
    return fastClz.getMethod(method);
}
 
Example #13
Source File: ServiceBeanFactory.java    From springtime with Apache License 2.0 4 votes vote down vote up
public MethodInvoker(Object implBean, FastMethod method) {
	requestParameterType = method.getParameterTypes()[0];
	this.method = method;
	this.implBean = implBean;
}
 
Example #14
Source File: FastMethodInvoker.java    From j360-dubbo-app-all with Apache License 2.0 4 votes vote down vote up
protected FastMethodInvoker(FastMethod fastMethod) {
	this.fastMethod = fastMethod;
}
 
Example #15
Source File: GenericVisitor.java    From api-compiler with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked") // ensure by construction
private FastMethod getMethod(Dispatcher<BaseType> dispatcher, BaseType instance) {
  Preconditions.checkNotNull(instance, "instance");
  return dispatcher.getMethod((Class<? extends BaseType>) instance.getClass());
}
 
Example #16
Source File: SetParameterFastMethodInvocation.java    From j360-tools with Apache License 2.0 4 votes vote down vote up
public SetParameterFastMethodInvocation(final FastMethod method, final Object[] arguments, final Object value) {
    super(method, arguments);
    this.index = (int) arguments[0];
    this.value = value;
}
 
Example #17
Source File: Dispatcher.java    From api-compiler with Apache License 2.0 4 votes vote down vote up
/**
 * Delivers the {@link FastMethod} which can handle an object of given type.
 * Delivers the method with most specific type, or null, if none exists.
 */
public FastMethod getMethod(Class<? extends BaseType> type) {
  Optional<FastMethod> result = dispatchTable.getUnchecked(type);
  return result.isPresent() ? result.get() : null;
}
 
Example #18
Source File: JdbcFastMethodInvocation.java    From j360-tools with Apache License 2.0 4 votes vote down vote up
public static FastMethod get(Method method) {
    return fastClz.getMethod(method);
}