samedi 11 novembre 2017

Class cast exception when casting an object generated by Relections library

Basically, what I want is to get all classes that implement an interface. But when I stream the list of objects returned by Reflections.getSubTypesOf, and do a cast, I got:

java.lang.ClassCastException: Cannot cast java.lang.Class to com.czetsuya.api.error.ExceptionToErrorCode

Here are some parts of the code:

Returns a list of classes that implement an interface from a package:

public static Set<Class<?>> getSubclasses(String packageName, Class parentClass) {
    Reflections reflections = new Reflections(packageName);
    return reflections.getSubTypesOf(parentClass);
}

Cast the returned list of objects:

private Stream<ExceptionToErrorCode> implementations() {
    return ReflectionUtils.getSubclasses("com.weddinghighway.api", ExceptionToErrorCode.class).stream().map(p -> {
        return ExceptionToErrorCode.class.cast(p);
    });
}

Performs filtering:

public ErrorCode of(Exception exception) {
    return implementations() //
        .filter(impl -> impl.canHandle(exception)) //
        .findFirst() //
        .map(impl -> impl.toErrorCode(exception)) //
        .orElse(ErrorCode.UnknownErrorCode.INSTANCE);
}

Note: I'm using a nested class, not sure if it's causing something:

public class GenericApiExceptionMappers {

    static class FileDoesNotExistsExceptionToErrorCode implements ExceptionToErrorCode {
        @Override
        public boolean canHandle(Exception exception) {
            return exception instanceof FileDoesNotExistsException;
        }

        @Override
        public ErrorCode toErrorCode(Exception exception) {
            return GenericApiErrorCodes.FILE_DOES_NOT_EXISTS;
        }
    }

    static class InvalidParameterExceptionToErrorCode implements ExceptionToErrorCode {
    }

}





Aucun commentaire:

Enregistrer un commentaire