[英]How to give access inside Groovy script to a field by adding getter for a field through an annotation
I have a model class with fields inside: 我有一个包含字段的模型类:
public class Model1 {
@Bind private int LL;
@Bind private double[] twKI;
@Bind private double[] twKS;
@Bind private double[] twINW;
@Bind private double[] twEKS;
}
I created 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 {
}
Is it possible to define getter and setters for fields inside Model1
class without modyfing it so later on they will by available in groovy script? 是否有可能为
Model1
类中的字段定义getter和setter而不对它进行修改,以便稍后在groovy脚本中提供它们?
Well you have multiple choices and you can choose whichever suits you better: 那么你有多种选择,你可以选择更适合你的选择:
We have a model object: Model model = new Model()
我们有一个模型对象:
Model model = new Model()
1. Using getter and setters : Create getters and setter methods and then call the setter method: model.setLL(10)
1.使用getter和setter :创建getter和setter方法,然后调用setter方法:
model.setLL(10)
2. Without getter and setters : Well in groovy/grails scope variables doesn't make much difference until you are overriding them for some specific purpose. 2.没有getter和setter :在groovy / grails范围变量中,除非为了某些特定目的而覆盖它们,否则没有多大区别。 So you can directly set the value using
model.LL = 10
所以你可以使用
model.LL = 10
直接设置值
3. Using setProperty : model.setProperty('LL', 10)
3.使用setProperty :
model.setProperty('LL', 10)
4. Reflection way : before setting the field value, mark it as accessible. 4.反射方式 :在设置字段值之前,将其标记为可访问。
Field field = Model.getDeclaredField("LL")
field.setAccessible(true)
field.set(model, 10)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.