簡體   English   中英

如何通過注釋使Groovy腳本中的私有字段可用

[英]How to make a private field available in Groovy script by an annotation

例如我有一個課:

public class Model1 {
  @Bind private int val;
}

我有一個注釋

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類的對象傳遞給Groovy腳本,但該腳本中沒有可用的val 我可以通過@Bind注釋使其可用嗎?

如果您的私有字段沒有訪問器,則實現所需目標的唯一方法是使用反射。

首先,獲取模型的所有字段:

Model1.getClass().getDeclaredFields()

它將返回已聲明字段的列表。 然后,遍歷列表並檢查是否用Bind注釋了字段:

field.getDeclaredAnnotation(Bind.class)

如果未使用'Bind'注釋對字段進行注釋,則此方法將返回null。

最后,使私有字段可訪問:

field.setAccessible(true);

現在,您需要與田野一起搏擊

暫無
暫無

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

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