This question is a follow up to a question I found before
java: get all variable names in a class
What I want is to get variables from a class, but instead of getting them all, I want only the variables that have the annotation @isSearchable
.
So basically I have 2 questions :
How do I create an annotation ?
How to filter my fields by only this annotation ?
And one more thing , if it is something I'm using frequently is it advisable (I'm guessing reflections should be slow).
Thank you
To access class variables, you use the same dot notation as with instance variables. To retrieve or change the value of the class variable, you can use either the instance or the name of the class on the left side of the dot.
Variable Annotation is basically an enhancement of type hinting, which was introduced in Python 3.5. The full explanation behind Variable Annotation is explained in PEP 526. In this article, we give have a quick refresher on type hinting and then introduce the new Variable Annotation syntax.
Annotations help to associate metadata (information) to the program elements i.e. instance variables, constructors, methods, classes, etc. Annotations are not pure comments as they can change the way a program is treated by the compiler.
The getAnnotation() method of java. lang. reflect. Field is used to return returns Field objects's for the specified type if such an annotation is present, else null.
/** Annotation declaration */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface isSearchable{
//...
}
@isSearchable
public String anyField = "any value";
checking like:
//use MyClass.class.getDeclaredFields() if you want the fields only for this class.
//.getFields() returns the fields for all the class hierarchy
for(Field field : MyClass.class.getFields()){
isSearchable s = field.getAnnotation(isSearchable.class);
if (s != null) {
//field has the annotation isSearchable
} else {
//field has not the annotation
}
}
Here is an example
class Test {
@IsSearchable
String str1;
String str2;
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface IsSearchable {
}
public static void main(String[] args) throws Exception {
for (Field f : Test.class.getDeclaredFields()) {
if (f.getAnnotation(IsSearchable.class) != null) {
System.out.println(f);
}
}
}
}
prints
java.lang.String Test.str1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With