0

Having a generic static function where I just have the generic types, it´s possible to get the Class of one of those generics?

Here my code:

     public static <A extends ResultError, B, A1 extends ResultError, B1> Function1<Either<A, B>,
                Either<A1, B1>> transformConnectorErrorVoToCommandError(Event event) {
            return new AbstractFunction1<Either<A, B>, Either<A1, B1>>() {

               @Override
                public Either<A1, B1> apply(Either<A, B> parameter) {
                    if (parameter.isRight()) {
                        return mapsRightSide(parameter);
                    } else {
                        return mapsLeftSide(parameter, event, ${I NEED THE CLASS OF A HERE});
                    }
                }

               Either<A1, B1> mapsRightSide(Either<A, B> parameter) {
                    return right(parameter.right().get());
                }

               Right right(Object result) {
                    return new Right<>(result);
                }

           };
        }

private static <A extends ResultError, B, A1 extends ResultError, B1> Either<A1, B1> mapsLeftSide(Either<A, B> parameter,
                                                                                                      Event event,
                                                                                                      Class<A1> outputErrorClass) {
        initLazyMapperComponent();
        A sourceError = parameter.left().get();
        A1 destinyError = mapper.map(sourceError, outputErrorClass);
        if (destinyError != null) {
            return left(destinyError);
        }
        ExceptionUtil.throwNotHandledError(event, sourceError);
        return null;
    }

the part that I need in the code is ${I NEED THE CLASS OF A HERE} I know that in a non static function it´s possible but not idea if can be done in a static way.

Regards.

paul
  • 12,873
  • 23
  • 91
  • 153
  • It doesn’t matter whether the method is `static` or not. There is no way. – Holger Oct 13 '17 at 10:24
  • Yea you can https://stackoverflow.com/questions/3437897/how-to-get-a-class-instance-of-generics-type-t – paul Oct 13 '17 at 11:37
  • Do you have a link to an answer that does something different than requiring a `Class` object, provided by the client code that knows the type (which, of course, would work with a `static` method as well)? – Holger Oct 13 '17 at 12:13

1 Answers1

2

No, you can't get the class of A there. It's all erased in the runtime.

Typical options are to get the type of A from the value of the instance of A which you probably have in the parameter anyway.

Or pass Class<A> classOfA as a further parameter.

lexicore
  • 42,748
  • 17
  • 132
  • 221