Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/380.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何使用ByteBuddy添加自定义get/set方法_Java_Byte Buddy - Fatal编程技术网

Java 如何使用ByteBuddy添加自定义get/set方法

Java 如何使用ByteBuddy添加自定义get/set方法,java,byte-buddy,Java,Byte Buddy,我目前正在尝试使用ByteBuddy作为java bean包装键/值对的java.util.Map,该java bean将映射键公开为普通的getter/setter 我最初按照如下方式构造生成器,允许我将映射作为构造函数参数传递: DynamicType.Builder builder = new ByteBuddy() .subclass( Object.class ) .name( customClassName ) .implement( Serializable.class

我目前正在尝试使用ByteBuddy作为java bean包装键/值对的
java.util.Map
,该java bean将映射键公开为普通的getter/setter

我最初按照如下方式构造生成器,允许我将
映射作为构造函数参数传递:

DynamicType.Builder builder = new ByteBuddy()
  .subclass( Object.class )
  .name( customClassName )
  .implement( Serializable.class )
  .defineField( "theMap", Map.class )
  .defineConstructor( Modifier.PUBLIC )
    .withParameters( Map.class )
    .intercept(
      MethodCall.invoke( Object.class.getConstructor() ).onSuper()
        .andThen( FieldAccessor.ofField( "theMap" ).setArgumentAt( 0 ) ) );
我不确定的是如何定义关联的getter/setter方法,以便它们有效地复制此行为:

public Integer getFoo() {
  return theMap.get( "foo" );
}

public void setFoo(Integer foo) {
  theMap.put( "foo", foo );
}
我从ByteBuddy那里了解到,我实际上会做类似的事情:

builder.defineMethod( "getFoo", Integer.class, Modifier.PUBLIC )
  .intercept( /* what goes here */ );

builder.defineMethod( "setFoo", Void.clss, Modifier.PUBLIC )
  .withParameters( Integer.class )
  .intercept( /* what goes here */ );

问题是拦截方法调用的内部是什么?

我最终是这样做的

// The Getter
builder = builder.defineMethod( "getFoo", Integer.class, Modifier.PUBLIC )
  .intercept(
    MethodCall.invoke( Map.class.getMethod( "get", Object.class ) )
      .onField( "theMap" )
      .with( propertyKey ) );

// The Setter
builder = builder.defineMethod( "setFoo", void.class, Modifier.PUBLIC )
  .withParameters( Integer.class )
  .intercept(
    MethodCall.invoke( Map.class.getMethod( "put", Object.class, Object.class ) )
      .onField( "theMap" )
      .with( propertyKey ) )
      .withArgument( 0 )
      .andThen( new Implementation.Simple( MethodReturn.VOID ) ) );
在这两种情况下,只需要将
MethodCall#invoke
委托给我正试图使用适当的Map键封装的相应
Map
方法


同样在set方法的情况下,将传入参数0(提供的setter方法的参数)委托给带有键的map方法调用也很重要

对于你的情况,这是完美的。或者,查看
建议
方法委派