简体   繁体   中英

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?

Well you have multiple choices and you can choose whichever suits you better:

We have a model object: Model model = new Model()

1. Using getter and setters : Create getters and setter methods and then call the setter method: 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. So you can directly set the value using model.LL = 10

3. Using setProperty : model.setProperty('LL', 10)

4. Reflection way : before setting the field value, mark it as accessible.

Field field = Model.getDeclaredField("LL")
field.setAccessible(true)
field.set(model, 10)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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