I'm assuming that your variable dbObj is a DBObject that has been retrieved from MongoDB, and I'm also assuming the ClassCastException is thrown on line 6 of your example code.
The problem is that you're casting on line 6 in your code sample, and you're casting to the wrong type. When you get something back from MongoDB, you don't get your Java objects back (i.e. Computer). Any document or sub-document in the database will come back as a BasicDBObject. And this cannot be cast to Computer.
What you need to do is take the relevant information out of the BasicDBObject and then create a new Computer out of it. So, say for example your Computer looks like this:
class Computer {
String name;
int ipAddress;
Computer(final String name, final int ipAddress) {
this.name = name;
this.ipAddress = ipAddress;
}
}
then you will probably want to do something like:
final BasicDBObject dbObj = null;
if (dbObj.get("computers") != null){
computerList = (BasicDBList) dbObj.get("computers");
}
for ( obj : computerList) {
final BasicDBObject computerAsDBObject = (BasicDBObject) obj;
final Computer computer = new Computer(computerAsDBObject.getString("name"),
computerAsDBObject.getInt("ipAddress"));
System.getComputers().add(computer);
}
When you're working with the Java driver directly, you will only get a very limited set of types back from the database - i.e. Strings, ints, longs and other primitives, and simple objects like BasicDBList and BasicDBObject.
What Abhishek was alluding to in the comment was that if you use an ODM like Morphia or Spring Data, you will get "real" Java objects like your Computer class back from Mongo, but you won't get that with the driver alone.
com.me.systems.commons.entities.Datathe correct path to the type?