简体   繁体   English

Java方法如何接受扩展通用类型的参数

[英]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. 我正在尝试将一个小型MongoDB应用程序实现为jar文件,该文件可以从一系列其他应用程序中使用。 (Running Java 6) (运行Java 6)

The purpose is to have a class that handles and contains DBCollection , MongoDatabase and MongoClient . 目的是拥有一个处理并包含DBCollectionMongoDatabaseMongoClient This superclass can be extended by these other applications and the MongoDB used from these. 这些超类可以被这些其他应用程序以及这些中使用的MongoDB扩展。 I would also like the other applications to implement an interface which contains 1 insertIntoDB() method. 我还希望其他应用程序实现一个包含1 insertIntoDB()方法的接口。 This insertIntoDB() method should take 1 parameter which would be another subclass and herein is my problem. insertIntoDB()方法应采用1个参数,该参数将是另一个子类,这是我的问题。 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/ 一些阅读: https : //docs.oracle.com/javase/tutorial/java/generics/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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