繁体   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