简体   繁体   English

使用ByteBuddy访问有关检测方法的参数的字段

[英]Accessing fields on parameters of instrumented method using ByteBuddy

I am trying to generate efficient property accessors at runtime. 我试图在运行时生成有效的属性访问器。 Specifically this means I am generating classes that implement the following interface using ByteBuddy: 具体来说,这意味着我正在使用ByteBuddy生成实现以下接口的类:

interface PropertyAccess<T> {
    void set(Object instance, T value);
    T get(Object instance);
}

Implementations should look something like this: 实现看起来应该是这样的:

class SomeProperty implements PropertyAccess<String> {
    public void set(Object o, String s) {
        ((SomeClass) o).setFoo(s);
    }
    public String get(Object o) {
        return ((SomeClass) o).getFoo();
    }
 }

Doing this for a getter/setter pair is easy ( getter and setter being the java.lang.reflect.Method objects for the actual getter and setter): 对getter / setter对执行此操作很容易( gettersetter是实际getter和setter的java.lang.reflect.Method对象):

new ByteBuddy()
    .subclass(Object.class)
    .implement(PropertyAccess<String>.class) // pseudo syntax, I am using Guava's TypeToken here in reality
    .method(named("get")).intercept(invoke(getter).onArgument(0))
    .method(named("set")).intercept(invoke(setter).onArgument(0).withArgument(1))

(I left out here the assigner typing that will allow the cast from Object to SomeClass ). (我在这里省略了分配器,它将允许从ObjectSomeClass )。

But now I want to also allow generating such a class for a directly accessed field and I cannot find a way to do so without writing a custom Implementation class, because FieldAccessor only allows access to fields of the generated class (or one of it's parents). 但是现在我还想允许为直接访问的字段生成这样的类,并且在没有编写自定义Implementation类的情况下我找不到这样做的方法,因为FieldAccessor只允许访问生成的类的字段(或其中一个父类) 。

Am I missing something? 我错过了什么吗?

You are right, there is currently no way to access a field rather then a method. 你是对的,目前没有办法访问字段而不是方法。 I think this should however be easy to fix by treating a field access similar to a getter or setter. 我认为通过处理类似于getter或setter的字段访问,这应该很容易解决。 I am tracking this limitation in ticket #225 . 我在机票#225中跟踪此限制。

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

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