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. Can I make it avaiable by @Bind
annotation?
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:
field.getDeclaredAnnotation(Bind.class)
this method will return null if field is not annotated with 'Bind' annotation.
And finally, make private field accessible:
field.setAccessible(true);
Now do watever you need with field
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.