1

I have the following abstract class:

public abstract class AbstractRepository<O, PK extends Serializable>{

protected EventDispatcher eventDispatcher;

protected GenericDao<O,PK> dao;

protected ApplicationPublisher publisher;

protected State state;

protected InternalPublisher internalPublisher;

@PostConstruct
private void initialise(){
    eventDispatcher.addHandler(this);
}

protected <T extends GenericDao<O,PK>> AbstractRepository(T dao, State state, ApplicationPublisher publisher, InternalPublisher internalPublisher, EventDispatcher eventDispatcher){
    this.dao = dao;
    this.state = state;
    this.publisher = publisher;
    this.internalPublisher = internalPublisher;
    this.eventDispatcher = eventDispatcher;
}


@HandleEvent
private void handleDataContributorCreatedEvent(DataContributorDeletedEvent event){

    List<O> stats = new ArrayList<O>();

    for(int x = -1 ; x < 50 ; x++){

        for (int y = 0 ; y < 360 ; y = y + 5){
            stats.add(**Need to instantiate paramater type O here**);
        }   

    }
    dao.save(stats);
}

}

Within the event handler method - I want to be able to create an instance of the Parameter Type, O - but not sure how do this. Any help regarding the best approach would be appreciated.

evandongen
  • 1,995
  • 17
  • 19
totalcruise
  • 1,343
  • 2
  • 13
  • 25

3 Answers3

0

You cannot do that because of type erasure in Java. Basically, there's no way to know the class of your O parameter in runtime.

As @pescis suggested, here are described ways to overcome this problem.

Community
  • 1
  • 1
pfyod
  • 617
  • 5
  • 11
0

You should create a constructor accepting a parameter

Class<O> class

object store it and when you need it use

class.getConstructor() and constructor.newInstance 

methods of the reflection API. That's because the generic types exist only on compile time, in bytecode all that stuff are just plain Objects.

Rubén
  • 524
  • 5
  • 22
0

You can try to use the List instance you have, something like this :

Class<?> clazz = (Class<?>) stats.getGenericInterface()[0];

then you can clazz.newInstance().

Disclaimer : not tested, but i'm pretty sure i've read somewhere that it works.

njzk2
  • 38,969
  • 7
  • 69
  • 107