簡體   English   中英

如何通過注釋為字段添加getter,從而將Groovy腳本內部的訪問權限提供給字段

[英]How to give access inside Groovy script to a field by adding getter for a field through an annotation

我有一個包含字段的模型類:

public class Model1 {
  @Bind private int LL; 
  @Bind private  double[] twKI; 
  @Bind private  double[] twKS; 
  @Bind private  double[] twINW; 
  @Bind private  double[] twEKS; 
}

我創建了一個注釋:

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類中的字段定義getter和setter而不對它進行修改,以便稍后在groovy腳本中提供它們?

那么你有多種選擇,你可以選擇更適合你的選擇:

我們有一個模型對象: Model model = new Model()

1.使用getter和setter :創建getter和setter方法,然后調用setter方法: model.setLL(10)

2.沒有getter和setter :在groovy / grails范圍變量中,除非為了某些特定目的而覆蓋它們,否則沒有多大區別。 所以你可以使用model.LL = 10直接設置值

3.使用setPropertymodel.setProperty('LL', 10)

4.反射方式 :在設置字段值之前,將其標記為可訪問。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM