简体   繁体   English

如何通过注释使Groovy脚本中的私有字段可用

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

For instance I have a class: 例如我有一个课:

public class Model1 {
  @Bind private int val;
}

and I have 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 {


}

I would like to pass an object of Model1 class to the Groovy script but I will not have the val available in that script. 我想将Model1类的对象传递给Groovy脚本,但该脚本中没有可用的val Can I make it avaiable by @Bind annotation? 我可以通过@Bind注释使其可用吗?

If you do not have accessors for your private field, the only way to achieve what you want is to use reflection. 如果您的私有字段没有访问器,则实现所需目标的唯一方法是使用反射。

First, get all fields of your model, : 首先,获取模型的所有字段:

Model1.getClass().getDeclaredFields()

It will return list of declared fields. 它将返回已声明字段的列表。 Then, iterate over list and check if field is annotated with Bind: 然后,遍历列表并检查是否用Bind注释了字段:

field.getDeclaredAnnotation(Bind.class)

this method will return null if field is not annotated with 'Bind' annotation. 如果未使用'Bind'注释对字段进行注释,则此方法将返回null。

And finally, make private field accessible: 最后,使私有字段可访问:

field.setAccessible(true);

Now do watever you need with field 现在,您需要与田野一起搏击

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何通过注释为字段添加getter,从而将Groovy脚本内部的访问权限提供给字段 - How to give access inside Groovy script to a field by adding getter for a field through an annotation Groovy:如何定义可使用参数调用的 java 并使其可用于 groovy Z2591C98B70119B519E18 - Groovy: How to define a java callable with parameters and make it available to groovy shell? 如何为实体中的修剪字段制作自定义注释? - How to make a custom annotation for trimmed field in entities? 使注释可用于泛型类型 - Annotation to make available generic type 在 Groovy 脚本中使用 @Field 变量 - Using of @Field variable in Groovy script java.lang.reflect.InaccessibleObjectException:无法将字段设为私有最终 java.util.Map sun.reflect.annotationHandler。 - java.lang.reflect.InaccessibleObjectException: Unable to make field private final java.util.Map sun.reflect.annotation.AnnotationInvocationHandler 如何使Java Private方法中的变量值对另一个java文件可用/可见? - How to make the value of a variable inside a Java Private method available/visible to another java file? 如何在java中运行groovy脚本? - How to run groovy script in java? 如果只有一个类,如何传递注释对象 <Annotation> 有空吗? - How to pass an Annotation object if there is only a Class<Annotation> is available? 如何通过反射 api 从 java 将值注入 groovy 脚本中的字段? - How to inject value into field in groovy script from java via reflection api?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM