net.sf.cglib.reflect.FastClass Java Examples

The following examples show how to use net.sf.cglib.reflect.FastClass. 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: SeiFactoryImpl.java    From tomee with Apache License 2.0 5 votes vote down vote up
void initialize(Object serviceImpl, ClassLoader classLoader) throws ClassNotFoundException {
    this.serviceImpl = serviceImpl;
    Class serviceEndpointBaseClass = classLoader.loadClass(serviceEndpointClassName);
    serviceEndpointClass = enhanceServiceEndpointInterface(serviceEndpointBaseClass, classLoader);
    Class[] constructorTypes = new Class[]{classLoader.loadClass(GenericServiceEndpoint.class.getName())};
    this.constructor = FastClass.create(serviceEndpointClass).getConstructor(constructorTypes);
    this.handlerInfoChainFactory = new HandlerInfoChainFactory(handlerInfos);
    sortedOperationInfos = new OperationInfo[FastClass.create(serviceEndpointClass).getMaxIndex() + 1];
    String encodingStyle = "";
    for (int i = 0; i < operationInfos.length; i++) {
        OperationInfo operationInfo = operationInfos[i];
        Signature signature = operationInfo.getSignature();
        MethodProxy methodProxy = MethodProxy.find(serviceEndpointClass, signature);
        if (methodProxy == null) {
            throw new ServerRuntimeException("No method proxy for operationInfo " + signature);
        }
        int index = methodProxy.getSuperIndex();
        sortedOperationInfos[index] = operationInfo;
        if (operationInfo.getOperationDesc().getUse() == Use.ENCODED) {
            encodingStyle = org.apache.axis.Constants.URI_SOAP11_ENC;
        }
    }
    //register our type descriptors
    Service service = ((ServiceImpl) serviceImpl).getService();
    AxisEngine axisEngine = service.getEngine();
    TypeMappingRegistry typeMappingRegistry = axisEngine.getTypeMappingRegistry();
    TypeMapping typeMapping = typeMappingRegistry.getOrMakeTypeMapping(encodingStyle);
    typeMapping.register(BigInteger.class, Constants.XSD_UNSIGNEDLONG, new SimpleSerializerFactory(BigInteger.class, Constants.XSD_UNSIGNEDLONG), new SimpleDeserializerFactory(BigInteger.class, Constants.XSD_UNSIGNEDLONG));
    typeMapping.register(URI.class, Constants.XSD_ANYURI, new SimpleSerializerFactory(URI.class, Constants.XSD_ANYURI), new SimpleDeserializerFactory(URI.class, Constants.XSD_ANYURI));
    //It is essential that the types be registered before the typeInfos create the serializer/deserializers.
    for (Iterator iter = typeInfo.iterator(); iter.hasNext(); ) {
        TypeInfo info = (TypeInfo) iter.next();
        TypeDesc.registerTypeDescForClass(info.getClazz(), info.buildTypeDesc());
    }
    TypeInfo.register(typeInfo, typeMapping);
}
 
Example #8
Source File: MethodProxy.java    From cglib with Apache License 2.0 5 votes vote down vote up
private static FastClass helper(CreateInfo ci, Class type) {
    FastClass.Generator g = new FastClass.Generator();
    g.setType(type);
    g.setClassLoader(ci.c2.getClassLoader());
    g.setNamingPolicy(ci.namingPolicy);
    g.setStrategy(ci.strategy);
    g.setAttemptLoad(ci.attemptLoad);
    return g.create();
}
 
Example #9
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 #10
Source File: FastMethodInvoker.java    From j360-dubbo-app-all with Apache License 2.0 5 votes vote down vote up
private static FastMethodInvoker build(final Class<?> clz, Method method) {
	FastClass fastClz = MapUtil.createIfAbsent(fastClassMap, clz, new MapUtil.ValueCreator<FastClass>() {
		@Override
		public FastClass get() {
			return FastClass.create(clz);
		}
	});

	return new FastMethodInvoker(fastClz.getMethod(method));
}
 
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: MethodExpression.java    From PoseidonX with Apache License 2.0 5 votes vote down vote up
/**
 * 根据参数获取函数
 */
private void resolveMethod(IExpression[] exprs)
{
    Class< ? >[] paramTypes = null;
    if (exprs != null)
    {
        //获得函数参数类型
        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 funcitonName = annotation == null ? declareClass.getSimpleName() : annotation.value();
        //运行时调用,和resolveType方法不同
        StreamingRuntimeException exception =
         new StreamingRuntimeException(ErrorCode.FUNCTION_UNSUPPORTED_PARAMETERS, funcitonName);
        LOG.error(ErrorCode.FUNCTION_UNSUPPORTED_PARAMETERS.getFullMessage(funcitonName));
        throw exception;
    }
    FastClass declaringClass =
        FastClass.create(Thread.currentThread().getContextClassLoader(), method.getDeclaringClass());
    fastMethod = declaringClass.getMethod(method);
}
 
Example #13
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 #14
Source File: InstantiationOptimizerAdapter.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
public InstantiationOptimizerAdapter(FastClass fastClass) {
	this.fastClass = fastClass;
}
 
Example #15
Source File: InstantiationOptimizerAdapter.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
	Class beanClass = ( Class ) in.readObject();
	fastClass = FastClass.create( beanClass );
}
 
Example #16
Source File: BytecodeProviderImpl.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
public ReflectionOptimizer getReflectionOptimizer(
		Class clazz,
        String[] getterNames,
        String[] setterNames,
        Class[] types) {
	FastClass fastClass;
	BulkBean bulkBean;
	try {
		fastClass = FastClass.create( clazz );
		bulkBean = BulkBean.create( clazz, getterNames, setterNames, types );
		if ( !clazz.isInterface() && !Modifier.isAbstract( clazz.getModifiers() ) ) {
			if ( fastClass == null ) {
				bulkBean = null;
			}
			else {
				//test out the optimizer:
				Object instance = fastClass.newInstance();
				bulkBean.setPropertyValues( instance, bulkBean.getPropertyValues( instance ) );
			}
		}
	}
	catch( Throwable t ) {
		fastClass = null;
		bulkBean = null;
		String message = "reflection optimizer disabled for: " +
		                 clazz.getName() +
		                 " [" +
		                 StringHelper.unqualify( t.getClass().getName() ) +
		                 ": " +
		                 t.getMessage();

		if (t instanceof BulkBeanException ) {
			int index = ( (BulkBeanException) t ).getIndex();
			if (index >= 0) {
				message += " (property " + setterNames[index] + ")";
			}
		}

		log.debug( message );
	}

	if ( fastClass != null && bulkBean != null ) {
		return new ReflectionOptimizerImpl(
				new InstantiationOptimizerAdapter( fastClass ),
		        new AccessOptimizerAdapter( bulkBean, clazz )
		);
	}
	else {
		return null;
	}
}
 
Example #17
Source File: FastMethodInvoker.java    From oxygen with Apache License 2.0 4 votes vote down vote up
public FastMethodInvoker(Object target, Method method) {
  this.target = target;
  this.method = FastClass.create(target.getClass()).getMethod(method);
}
 
Example #18
Source File: MethodProxy.java    From cglib with Apache License 2.0 4 votes vote down vote up
FastClass getFastClass() {
  init();
  return fastClassInfo.f1;
}
 
Example #19
Source File: MethodProxy.java    From cglib with Apache License 2.0 4 votes vote down vote up
FastClass getSuperFastClass() {
  init();
  return fastClassInfo.f2;
}