Ceasar
Ceasar

Reputation: 23073

In Java, what does object.class do?

I'm working with Google GSON, and in the docs they mention they following:

Object Examples

class BagOfPrimitives {
  private int value1 = 1;
  private String value2 = "abc";
  private transient int value3 = 3;
  BagOfPrimitives() {
    // no-args constructor
  }
}

(Serialization)

BagOfPrimitives obj = new BagOfPrimitives();
Gson gson = new Gson();
String json = gson.toJson(obj);  
==> json is {"value1":1,"value2":"abc"}

Note that you can not serialize objects with circular references since that will result in infinite recursion.

(Deserialization)

BagOfPrimitives obj2 = gson.fromJson(json, BagOfPrimitives.class);   
==> obj2 is just like obj

At the very bottom, they use BagOfPrimitives.class. What does that do exactly? (I would imagine it might return the class, but in that case I'd expect the code just to omit the '.class').

Upvotes: 0

Views: 190

Answers (2)

user219882
user219882

Reputation: 15844

You put a type in the method so you don't have to cast it. The fromJson method is generic and resolves the type itself according to the type you write in there...

<T> T fromJson(String json, Class<T> classOfT)

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500495

It's a class literal - it gives a reference to the Class object representing the particular class. See section 15.8.2 of the JLS for more details. For example:

String text = "Hello";
Class<?> classFromObject = text.getClass();
Class<?> classFromLiteral = String.class;
System.out.println(classFromObject == classFromLiteral); // true

In the case of the deserialization, it's to tell the deserializer what type to use to try to deserialize the data as.

Upvotes: 4

Related Questions