[英]How to make a private field available in Groovy script by an annotation
For instance I have a class: 例如我有一个课:
public class Model1 {
@Bind private int val;
}
and I have an annotation 我有一个注释
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 {
}
I would like to pass an object of Model1
class to the Groovy script but I will not have the val
available in that script. 我想将
Model1
类的对象传递给Groovy脚本,但该脚本中没有可用的val
。 Can I make it avaiable by @Bind
annotation? 我可以通过
@Bind
注释使其可用吗?
If you do not have accessors for your private field, the only way to achieve what you want is to use reflection. 如果您的私有字段没有访问器,则实现所需目标的唯一方法是使用反射。
First, get all fields of your model, : 首先,获取模型的所有字段:
Model1.getClass().getDeclaredFields()
It will return list of declared fields. 它将返回已声明字段的列表。 Then, iterate over list and check if field is annotated with Bind:
然后,遍历列表并检查是否用Bind注释了字段:
field.getDeclaredAnnotation(Bind.class)
this method will return null if field is not annotated with 'Bind' annotation. 如果未使用'Bind'注释对字段进行注释,则此方法将返回null。
And finally, make private field accessible: 最后,使私有字段可访问:
field.setAccessible(true);
Now do watever you need with field 现在,您需要与田野一起搏击
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.