[英]How to give access inside Groovy script to a field by adding getter for a field through an annotation
[英]How to make a private field available in Groovy script by an annotation
例如我有一个课:
public class Model1 {
@Bind private int val;
}
我有一个注释
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Bind {
}
我想将Model1
类的对象传递给Groovy脚本,但该脚本中没有可用的val
。 我可以通过@Bind
注释使其可用吗?
如果您的私有字段没有访问器,则实现所需目标的唯一方法是使用反射。
首先,获取模型的所有字段:
Model1.getClass().getDeclaredFields()
它将返回已声明字段的列表。 然后,遍历列表并检查是否用Bind注释了字段:
field.getDeclaredAnnotation(Bind.class)
如果未使用'Bind'注释对字段进行注释,则此方法将返回null。
最后,使私有字段可访问:
field.setAccessible(true);
现在,您需要与田野一起搏击
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.