调用getActualTypeArguments时松开泛型类型参数

时间:2018-03-23 11:52:00

标签: java generics

public class RemoveCategoryCommandHandler extends BaseCommandHandler<Categenter code hereory>
    implements CommandHandler<RemoveCategory> {

        public RemoveCategoryCommandHandler(RepositoryFactory repositoryfactory) {
        super(repositoryfactory);
        }


        public abstract class BaseCommandHandler<T extends AggregateRoot> {

            protected final Repository<T> repository;

            protected BaseCommandHandler(RepositoryFactory repositoryfactory) {
                this.repository = repositoryfactory.<T>create();
            }

        }


        public class RepositoryFactory {
            private final EventStore eventstore;
            private final EventPublisher eventPublisher;

            public RepositoryFactory(EventStore eventstore, EventPublisher eventPublisher) {
                this.eventstore = eventstore;
                this.eventPublisher = eventPublisher;
            }
            public <T extends AggregateRoot> Repository<T> create() {

                return new AggregateRepository<T>(eventstore, eventPublisher) {
                    @Override
                    public void save(T aggregate, int version) {
                        super.save(aggregate, version);
                    }
                };
            }
        }
    }
  

鉴于上面的场景,我在RemoveCategoryCommandHandler中   传递一个RepositoryFactory,它返回一个AgreegateRepository   输入T。

     

当我在存储库中调用以下代码clazz = getclass()时。

 ParameterizedType pt = (ParameterizedType) clazz.getGenericSuperclass();
            @SuppressWarnings("unchecked")
              Class<? extends AggregateRoot> parameterizedClazz = (Class<? extends AggregateRoot>) pt.getActualTypeArguments()[0];

repository = new AggregateRepository<Category>(store, new SimpleEventPublisher(resolver)) {
    @Override
    public void save(Category aggregate, int version) {
        super.save(aggregate, version);
    }
};
  

我收到以下错误       java.lang.ClassCastException:sun.reflect.generics.reflectiveObjects.TypeVariableImpl无法强制转换   到java.lang.Class

但如果我直接使用处理程序中的代码就可以了。 为什么我会丢失参数类型?

1 个答案:

答案 0 :(得分:1)

您没有丢失参数类型。你可以通过pt.getActualTypeArguments()[0]返回它。

但是,而不是(出于某种原因你所期望的)Class,返回的类型参数是TypeVariable。这是正确的。

Class检查getBounds()