【发布时间】:2017-04-03 06:40:30
【问题描述】:
如何使用字节伙伴在字段上创建设置器?推荐的语法是什么?
我设法从一个字段创建了 getter(我最初的问题 here),但是使用 defineMethod 创建一个 setter 会引发 Method Implementation.Context.Default ... is no bean property 异常。
在this 问题中创建设置器的建议方法似乎已过时。
这是我使用 byte-buddy 1.5.4 版的失败代码:
public static void main(String[] args) throws InstantiationException, IllegalAccessException, NoSuchFieldException, SecurityException, NoSuchMethodException {
Class<?> type = new ByteBuddy()
.subclass(Object.class)
.name("domain")
.defineField("id", int.class, Visibility.PRIVATE)
.defineMethod("getId", int.class, Visibility.PUBLIC).intercept(FieldAccessor.ofBeanProperty())
.defineMethod("setId", Void.TYPE, Visibility.PUBLIC).intercept(FieldAccessor.ofBeanProperty())
.make()
.load(sample.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)
.getLoaded();
Object o = type.newInstance();
Field f = o.getClass().getDeclaredField("id");
f.setAccessible(true);
System.out.println(o.toString());
Method m = o.getClass().getDeclaredMethod("getId");
System.out.println(m.getName());
Method s = o.getClass().getDeclaredMethod("setId", int.class);
System.out.println(s.getName());
}
【问题讨论】:
标签: java code-generation byte-buddy