简体   繁体   English

使用invokedynamic时的泛型信息

[英]Generics information when using invokedynamic

I am creating a java framework to convert beans with the help of Invoke dynamic. 我正在创建一个java框架,以便在Invoke dynamic的帮助下转换bean。 I create the convert class with ASM. 我用ASM创建转换类。 In order to generate a conversion which looks like: 为了生成如下所示的转换:

target.setter( convert(source.getter()) );

I write the following bytecode with ASM: 我用ASM编写以下字节码:

mv.visitVarInsn(ALOAD, ARGUMENT_2);
mv.visitVarInsn(ALOAD, ARGUMENT_1);
mv.visitMethodInsn(INVOKEVIRTUAL, sourceClass, sourceGetter.getName(), Type.getMethodDescriptor(sourceGetter), false);
mv.visitInvokeDynamicInsn("convert", Type.getMethodDescriptor(Type.getType(targetSetter.getParameterTypes()[0]), Type.getType(sourceGetter.getReturnType())), converterBootstrapMethod);
mv.visitMethodInsn(INVOKEVIRTUAL, targetClass, targetSetter.getName(), Type.getMethodDescriptor(targetSetter), false);

The convert method then searches for a converter that can handle the given types. 然后,convert方法搜索可以处理给定类型的转换器。 This looks like: 这看起来像:

public static CallSite bootstrap(final MethodHandles.Lookup caller, final String name, final MethodType type) throws Exception {
    final Class<?> sourceType = type.parameterType(0);
    final Class<?> targetType = type.returnType();
    MethodHandle converter = findConverter(sourceType, targetType);
    return new ConstantCallSite( converter.asType(type) );
}

This works fine for say String to Integer conversion. 这适用于String to Integer转换。 But not for generics. 但不适用于仿制药。 The sourceType is only Ljava/util/List; sourceType只是Ljava/util/List; and not the full Ljava/util/List<Ljava/lang/String;>; 而不是完整的Ljava/util/List<Ljava/lang/String;>;

How can I get the full type in this bootstrap method? 如何在此引导方法中获取完整类型?

If you are in control of your invoke dynamic call site, you are able to pass additional arguments to it. 如果您可以控制调用动态调用站点,则可以向其传递其他参数。 Within these arguments, you would need to pass the actual field/getter names and their declaring classes to the callsite. 在这些参数中,您需要将实际的字段/ getter名称及其声明类传递给调用点。

Using this information within your bootstrap method, you can now locate the actual fields/getters and extract the generic information via the reflection API. 在引导方法中使用此信息,您现在可以找到实际的字段/ getter并通过反射API提取通用信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM