lundi 18 mars 2019

is it possible to read variable values using it's annotation class

The following code is my annotation class

   import java.lang.annotation.Documented;
   import java.lang.annotation.ElementType;
   import java.lang.annotation.Retention;
   import java.lang.annotation.RetentionPolicy;
   import java.lang.annotation.Target;
   @Documented
   @Target(ElementType.FIELD)
   @Retention(RetentionPolicy.RUNTIME)
   public @interface Search {
     public String name();
     public String value();
   }
Following class is a normal class

  public class MyClass{

  @Search(name = "first_name", value = "srivas")
  private String first_name;
  @Search(name = "last_name", value = "sam")
  private String last_name;

  public String getFirst_name() {
    return first_name;
  }
  public void setFirst_name(String customername) {
    this.customername = customername;
  }
  public String getLast_name() {
    return last_name;
  }
  public void setLast_name(String last_name) {
    this.last_name= last_name;
  }
 }

Here I am going to read variable values

MyClass myvals = new MyClass();
myvals.setFirst_name("Vikram");
myvals.setLast_name("Kumar");
for(Field f: Customer.class.getDeclaredFields()){
             MyClass searchfields = f.getAnnotation(MyClass.class);
             Value val = f.getAnnotation(Value.class);
             if (searchfields != null)
             System.out.println(searchfields.name()+" = "+val.value());

        }

I am getting the following output first_name = srivas, last_name = sam,

but I am expecting.

first_name = vikram, last_name = Kumar,

Is it possible to read please help me if any posibility is there





Aucun commentaire:

Enregistrer un commentaire