简体   繁体   中英

How can a java method take an argument that extends a generic type

I'm trying to implement a small MongoDB application as a jar file which can be used from a series of other applications. (Running Java 6)

The purpose is to have a class that handles and contains DBCollection , MongoDatabase and MongoClient . This superclass can be extended by these other applications and the MongoDB used from these. I would also like the other applications to implement an interface which contains 1 insertIntoDB() method. This insertIntoDB() method should take 1 parameter which would be another subclass and herein is my problem. How can the interface specify an extension of a generic type so that each implementation returns the extended types ?

Below is a bit further explanation:

class AsuperClass implements Ainterface {
  MongoClient aMongoClient
  MongoDatabase aMongoDatabase
  initMongoDb() {
    //doStuff
  }
}

class AsuperPojo {
  int propA
  String propB
}

interface Ainterface {
  void insertToDb(AsuperPojo); 
}

class SubClass1 implements Ainterface extends AsuperClass{
  @Override
  public void insertToDb(SpecialSubClass1Pojo aSpecialSubClass1Pojo) {
    //doStuff
  }
}

class SpecialSubClass1Pojo() {
  int propA
  String propB
}

class SubClass2 implements Ainterface extends AsuperClass{
  @Override
  public void insertToDb(SpecialSubClass2Pojo aSpecialSubClass2Pojo) {
    //doStuff
  }
}

class SpecialSubClass2Pojo() {
  int propA
  String propB
}

Maybe there's a completely different way of doing this?

If I did understand well, you are looking for this:

interface Ainterface<T extends AsuperPojo>  {
  void insertToDb(T foo); 
}

then use:

class SubClass2 implements Ainterface<SpecialSubClass2Pojo>

Some reading: https://docs.oracle.com/javase/tutorial/java/generics/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM