简体   繁体   中英

MongoDB Java-Driver: Cannot extend MongoDatabase

i'm coding on a MongoDB java application.

I want to create a Collection of the objects (Type MongoDatabase) of every database from the mongoClient. Check

Next step: i want to extend the Type MongoDatabase to code some functions for my own. Folling error comes up: java.lang.ClassCastException: com.mongodb.MongoDatabaseImpl cannot be cast to model.ownMongoDatabase

I don't know why, but the old Java-driver has an DB-Class. Some changes are made to the Java-Driver (Version 3), and the function for the DB-Class are now marked as deprecated. Now you apperently have to use MongoDatabase. But MongoDatabase is an Interface, so no chance to extend it for my own Class?!

Code Snippet:

public class MongodbInstance extends com.mongodb.MongoClient {

 private ArrayList<ownMongoDatabase > _mongodbDatabases = new ArrayList<ownMongoDatabase >();

 private void buildMongodbDatabases(){
   MongoCursor<String> iterator = this.listDatabaseNames().iterator(); // iterate through Databases

   while(iterator.hasNext()){
     this._mongodbDatabases.add((ownMongoDatabase) this.getDatabase(iterator.next())); // add Database-Object to Array
     }
   }
}


class ownMongoDatabase implements MongoDatabase {

}

Is there an tought mistake/coding failure? Thanks for your help.

this._mongodbDatabases.add((ownMongoDatabase) this.getDatabase(iterator.next()));

In this line you are trying to assign MongoDatabaseImpl to your ownMongoDatabase. This will for sure throw class cast exception.

Suppose you have class A which is parent class, Class B and Class C extends from Class A. You cannot assign class B to class C.

Try has-A relationship instead of is-A relationship.

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