Lahiru Jayakody
Lahiru Jayakody

Reputation: 5410

Array of annotations as a javassist annotation member

I'm trying to create following annotation dynamically using javassist. I couldn't find a way to add array of annotations ({@JoinColumn, @JoinColumn}) as a javassist annotation member. Any suggessions?

@ManyToOne
@JoinColumns({
        @JoinColumn,
        @JoinColumn
})
private Parent parent;

Here are some references to build simple annotations.

AnnotationAttribute
Dynamically Adding annotations
Annotations at runtime

Upvotes: 1

Views: 305

Answers (1)

Lahiru Jayakody
Lahiru Jayakody

Reputation: 5410

Here I'm answering my own question.

/*
 * parentAnnotation, @JoinColumns object
 * memberName, "value"
 * memberValue, {@JoinColumn,...} object
 */ 
public void addMemberToAnnotation(Annotation parentAnnotation String memberName, Object memberValue){
    if(memberValue instanceof Annotation[]){
        ArrayList<AnnotationMemberValue> members = new ArrayList<AnnotationMemberValue>();
        AnnotationMemberValue annotationValue;
        for (Annotation a:(Annotation[])memberValue) {
            annotationValue =  new AnnotationMemberValue(cb.getCpool());
            annotationValue.setValue(a);
            members.add(annotationValue);
        }
        ArrayMemberValue arrayValue = new ArrayMemberValue(cb.getCpool());
        arrayValue.setValue(members.toArray(new MemberValue[0]));
        parentAnnotation.addMemberValue(memberName, arrayValue);
    } else if ( ... ){
        // Other cases
    }
}

Upvotes: 1

Related Questions