lundi 9 janvier 2017

Getting Enum class from generic type?

Suppose I have several classes:

Class ExceptionA{
    public ExceptionA(ExceptionA.ErrorCode errorCode){}
    setters...
    getters...
    public static enum ErrorCode{
        EC_ABC,EC_XYZ,EC_123
}

Class ExceptionB{
    public ExceptionB(ExceptionB.ErrorCode errorCode){}
    setters...
    getters...
    public static enum ErrorCode{
        EC_DEF,EC_LOL,EC_456
}

In a loop somewhere that works with an array containing ExceptionA, ExceptionB, ExceptionC objects: I want to generically construct an Exception object using its constructor without ever explicitly stating ExceptionX.ErrorCode.

Class<? extends Exception> expectedException = exception.getClass().getConstructor(Enum.class).newInstance(someErrorCodeEnum);

The issue occurs at getConstructor(). Constructors do exist for each Exception class, but they take SpecificException.ErrorCode type. Not just a generic Enum.class. Is there some method that might work like this?:

ExceptionA exceptionAobject = new ExceptionA(EC_ABC);
exceptionAobject.getEnumClassFromString("ErrorCode"); // Should be of type ExceptionA.ErrorCode





Aucun commentaire:

Enregistrer un commentaire