jeudi 1 février 2018

How to find if an enum implementing an interface has overriden the methods?

I am trying to use Reflection to determine which types of my enumerator are valid for the data I need to send. The structure is below. I am taking the MyEnum type as input to my service which informs me what type of request I am dealing with and what I need to do in order to the process that data.

So I am checking that the value they give me does match MyEnum by:

return value != null ? MyEnum.valueOf(value.trim().toUppercase()) != null : false;

However, I am NOT validating if the MyEnum instance they requested has method1 and method2 implementations or if it will default to throw UnsupportedOperationException. I tried reflection on the class to gather the Override annotations, but I don't know how to reflect on the methods declared inside the annoyomous enum classes like TYPE_A or TYPE_B. My reflection attempts keep scanning MyEnum.class and not the annoyomous classes I want to.

How can I check if the implementation exists without invoking the methods? Here is my code.

public interface MyEnumInterface {

    default MyRequest method1(MyRequest request){
        throw new UnsupportedOperationException("The operation you are trying to do is not yet supported!");
    }
    default boolean method2(MyRequest request){
        throw new UnsupportedOperationException("The operation you are trying to do is not yet supported!");
    }
}

public enum MyEnum implements MyEnumInterface  {

    TYPE_A {
        @Override
        public MyRequest method1(MyRequest request){
            // Logic
            request.setStatus("SAVING");
            return MyRequestService.persist(request);
        }
        @Override
        public boolean method2(MyRequest request){
            request.setStatus("PROCESSING");
            // Logic...
            return true;
        }
    },
    TYPE_B {
        @Override
        public MyRequest method1(MyRequest request){
            // Different Logic...
            return request;
        }
    },
    TYPE_C {
    };
}  





Aucun commentaire:

Enregistrer un commentaire