简体   繁体   English

在Java中,object.class有什么作用?

[英]In Java, what does object.class do?

I'm working with Google GSON, and in the docs they mention they following: 我正在使用Google GSON,在文档中他们提到了以下内容:

 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 . 在最底部,他们使用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'). (我想它可能会返回该类,但是在那种情况下,我希望代码只是省略'.class')。

It's a class literal - it gives a reference to the Class object representing the particular class. 这是一个类文字 -它提供了对表示特定类的Class对象的引用。 See section 15.8.2 of the JLS for more details. 有关更多详细信息,请参见JLS的15.8.2节 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. 在反序列化的情况下,是告诉反序列化器尝试使用哪种类型对数据进行反序列化。

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... fromJson方法是通用的,并根据您在其中编写的类型来解析类型本身。

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

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

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