我正在创建一个java框架来在Invoke dynamic的帮助下转换bean。我用ASM创建了转换类。为了生成如下所示的转换:
target.setter( convert(source.getter()) );我用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);然后,convert方法搜索可以处理给定类型的转换器。这看起来像这样:
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) );
}这对于字符串到整数的转换很有效。但不适用于泛型。sourceType仅为Ljava/util/List;,而不是完整的Ljava/util/List<Ljava/lang/String;>;
如何在这个bootstrap方法中获得完整的类型?
发布于 2016-07-02 16:14:24
如果您控制了调用动态调用站点,则可以向其传递额外的参数。在这些参数中,您需要将实际的字段/getter名称及其声明类传递给调用站点。
使用bootstrap方法中的这些信息,您现在可以定位实际的字段/getter,并通过反射API提取通用信息。
https://stackoverflow.com/questions/38149020
复制相似问题