mardi 28 juin 2022

Java - Not able to get value of Custom Annotation using Reflection

I'm trying to generate a report and the fields should be in the specified sequence. As this is microservices architecture, I've a db service where interface based projection is used. On top of it, I'm trying to use a custom annotation to maintain the order.

Custom Annotation:

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Sequence {
        int value();
}

Interface based Projection DTO :

public interface ReportDTO {

@Sequence(value = 1)
String getId();

@Sequence(value = 2)
String getName();

@Sequence(value = 3)
String getMobileNumber();

}

In another micoservice, I'm deploying this db service and utilising as below:

private static List<String> getFieldNamesForClass(Class<?> clazz) throws Exception {
    List<String> fieldNames = new ArrayList<String>();
    Method[] methods = clazz.getMethods();

    Arrays.sort(methods, (o1, o2) -> {
        boolean isPresent = o1.isAnnotationPresent(Sequence.class);
        
        Sequence or1 = o1.getAnnotation(Sequence.class);
        Sequence or2 = o2.getAnnotation(Sequence.class);
        // nulls last
        if (or1 != null && or2 != null) {
            return or1.value() - or2.value();
        } else
        if (or1 != null && or2 == null) {
            return -1;
        } else
        if (or1 == null && or2 != null) {
            return 1;
        }
        return o1.getName().compareTo(o2.getName());
    });
    for (Method method : methods) {
        if (method.getName().substring(0, 3).equals("get") && !method.getName().equals("getDecoratedClass")
                && !method.getName().equals("getTarget") && !method.getName().equals("getTargetClass"))
            fieldNames.add(lowerFirst(method.getName().substring(3)));
    }
   
    return fieldNames;
}

But this code is unable to figure out the annotation. Variable "isPresent" returns false and or1 and or2 are null. Please help me figure out the issue with this code.





Aucun commentaire:

Enregistrer un commentaire