Shenglei Zheng
Shenglei Zheng

Reputation: 3

Access to class attributes' values using Java Annotations

I am working with a java example using annotations, I created a simple POJO (java bean) using annotations to its attributes. I want to have the ability to create new objects of this type and retrieve the values of its attributes using the annotations created.

My POJO :

import java.io.Serializable;

import annotations.BusinessObject;
import annotations.BusinessObjectAttribute;
import annotations.BusinessObjectName;
import annotations.BusinessObjectPolicy;
import annotations.BusinessObjectRevision;
import annotations.BusinessObjectVault;

@BusinessObject
public class IndusTask implements Serializable{

/**
 * 
 */
private static final long serialVersionUID = 1L;


// Mandatory to create new object !
@BusinessObjectName
private String taskName;
@BusinessObjectRevision
private String taskRevision;
@BusinessObjectVault
private String vault;
// Mandatory to invoke iTask.create(context, policy) in Database
@BusinessObjectPolicy
private String policy;

//Specific attributes
@BusinessObjectAttribute
private String taskDescription;
@BusinessObjectAttribute
private String creationDate;
@BusinessObjectAttribute
private Integer weight;

public IndusTask() {
}

public IndusTask(String taskName, String taskRevision, String vault, String policy, String taskDescription,
        String creationDate, Integer weight) {
    super();
    this.taskName = taskName;
    this.taskRevision = taskRevision;
    this.vault = vault;
    this.policy = policy;
    this.taskDescription = taskDescription;
    this.creationDate = creationDate;
    this.weight = weight;
}

public String getTaskName() {
    return taskName;
}

public void setTaskName(String taskName) {
    this.taskName = taskName;
}

public String getTaskRevision() {
    return taskRevision;
}

public void setTaskRevision(String taskRevision) {
    this.taskRevision = taskRevision;
}

public String getVault() {
    return vault;
}

public void setVault(String vault) {
    this.vault = vault;
}

public String getTaskDescription() {
    return taskDescription;
}

public void setTaskDescription(String taskDescription) {
    this.taskDescription = taskDescription;
}

public String getCreationDate() {
    return this.creationDate;
}

public void setCreationDate(String creationDate) {
    this.creationDate = creationDate;
}

public Integer getWeight() {
    return weight;
}

public void setWeight(Integer weight) {
    this.weight = weight;
}

public String getPolicy() {
    return policy;
}

public void setPolicy(String policy) {
    this.policy = policy;
}

}

Example of attributes' declaration: *Business Object Type declaration

package annotations;

import java.lang.annotation.*;

//@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface BusinessObject {

}

*Business Object Name Attribute:

package annotations;

import java.lang.annotation.*;

//@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface BusinessObjectName {

}

I Created a main to test if all the annotations are detected:

public class MainImpl {

    public static void main(String[] args) {
        // TODO Auto-generated method stub


        IndusTask myTask = new IndusTask("mytstTask", "001", "eService Production", "TstTask Process",
                "myTstTask Description", "2018/02/16@15:30:10:GMT", 200);

        System.out.println(myTask.getClass().getAnnotations().length);

    }

}

Output is displaying 1 ! so only the first annotation is detected !

I was told also that the object attributes values can be accessed using these annotation (something similar to) :

object.getClass().getAnnotations()

How can i do ?

Upvotes: 0

Views: 1402

Answers (2)

Oleg Sklyar
Oleg Sklyar

Reputation: 10092

You need to iterate through the fields, get their annotations and set the value wherever the annotation matches (it can match multiple fields):

@Retention(RetentionPolicy.RUNTIME)
public @interface Field1 {}

@Retention(RetentionPolicy.RUNTIME)
public @interface Field2 {}

public static class UnderTest {

    @Field1
    private String field1;

    @Field2
    private int field2;

    public UnderTest(String field1, int field2) {
        this.field1 = field1;
        this.field2 = field2;
    }

    @Override
    public String toString() {
        return field1 + "=" + field2;
    }
}

public static void setter(Object obj, Class<? extends Annotation> fieldAnnotation, Object fieldValue) throws IllegalAccessException {
    for (Field field: obj.getClass().getDeclaredFields()) {
        for (Annotation annot: field.getDeclaredAnnotations()) {
            if (annot.annotationType().isAssignableFrom(fieldAnnotation)) {
                if (!field.isAccessible()) {
                    field.setAccessible(true);
                }
                field.set(obj, fieldValue);
            }
        }
    }
}

public static void main(String[] argv) throws IllegalAccessException {
    UnderTest underTest = new UnderTest("A", 1);
    System.out.println(underTest);

    setter(underTest, Field1.class, "B");
    setter(underTest, Field2.class, 2);
    System.out.println(underTest);
}

Running this prints

A=1

B=2

Upvotes: 1

df778899
df778899

Reputation: 10931

Sounds like you're after the annotations on the fields too?

E.g. for the first private field:

myTask.getClass().getDeclaredFields()[0].getAnnotations()

Note depending how you're accessing a private field, you will sometimes also need to first ensure it is accessible:

...getDeclaredFields()[0].setAccessible(true);

[edit] The values are reachable too from the fields. A basic worked example:

for (Field f : myTask.getClass().getDeclaredFields()) {
    f.setAccessible(true);
    System.out.println(f.getName() + "=" + f.get(myTask));  
    System.out.println("  annotations=" + java.util.Arrays.toString(f.getAnnotations()));   
}

Upvotes: 0

Related Questions