不寻常的语法用于对象构造

huangapple go评论76阅读模式
英文:

Unusual syntax used for object construction

问题

以下是您要求的翻译内容:

我对Java编程还不熟悉。在阅读一个开源项目的代码时,我遇到了一行代码,我无法理解:

final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();

我的问题是:

  1. 我通常会像这样调用构造函数:final Type typeOfMap = new TypeToken<Map<String, Object>>()。我从未见过后面跟着其他代码,比如{}.getType()。这是什么样的语法?
  2. {}是一个对象吗?为什么可以在它上面调用一个函数?

附注:Typejava.lang.reflect.TypeTypeTokencom.google.gson.reflect.TypeToken

英文:

I'm new to Java programming. While reading through the code of an open source project, I came across a line of code which I can't understand:

final Type typeOfMap = new TypeToken&lt;Map&lt;String, Object&gt;&gt;() {}.getType();

My questions are:

  1. I usually call a constructor like this: final Type typeOfMap = new TypeToken&lt;Map&lt;String, Object&gt;&gt;(). I have never seen it followed by other pieces of code such as {}.getType(). What kind of syntax is this?
  2. Is {} an object? Why can you call a function on it?

P.S. Type is java.lang.reflect.Type, and TypeToken is com.google.gson.reflect.TypeToken.

答案1

得分: 1

我对Java也不是很了解,但据我所知,那是属于一个抽象通用类 new TypeToken<Map<String, Object>>() {} 的构造函数。这个类本身可能类似于这样:public abstract class TypeToken<X>... 现在,对于方法 .getType(),我不太确定它是如何编码的。

你提醒了我,这是我要学习/了解的事情清单中的一项,但我相当确定这种代码模式有点过于工程化,(当然,这可能是因为我不了解它或者不知道它有什么用途)。

.getType() 方法可能是抽象类中的一个公共非抽象方法。

我个人发现在某些情况下(仅限于某些情况),实例化抽象对象比扩展抽象对象更方便(通常是如此),特别是在抽象对象在特定生命周期内需要另一个对象创建的情况下,或者在同一个类内部需要互操作性的情况下。

现在,如果我没有弄错的话,我认为该特定实现 com.google.gson.reflect.TypeToken 利用反射来获取尚未初始化对象的类类型,而不实际创建对象(可能在幕后执行),如果你尝试创建一个嵌套通用类数组的新实例,你会知道由于某种叫做“擦除”的东西,它可能会变得很头疼。

英文:

I'm also new at Java, but, as far as I know, that is a constructor that belongs to an abstract generic class new TypeToken&lt;Map&lt;String, Object&gt;&gt;() {} The class tiself may look something like this: public abstract class TypeToken&lt;X&gt; ... now, for the method .getType(). I'm not really sure how that is coded.
You reminded me that this is in my bucket list of things to learn/understand, but I'm pretty sure that this code pattern is a little too over engineered, (ofc this may be my bias precisely because I dont know it or what it could be useful for)

the .getType() method, may be a method inside the abstract that is public and non abstract.

I personally have found that in some cases (just in some), it is more convenient to instantiate abstract objects instead of extending them (which is how they are usually used), specially in cases when your abstract object needs another object created at an specific lifecycle, or when the abstract object needs interoperability within the same class.

Now If I'm not mistaken, I Think that THAT specific implementation com.google.gson.reflect.TypeToken makes use of reflect in order to get the class type of a non initialized object, without actually creating an object (maybe it does behind curtains), if you've tried to make a newInstance of an Array of nested generic classes, you know how it can become a headache, because of something called "erasure".

答案2

得分: 0

以下是翻译好的部分:

我通常这样调用构造函数:final Type typeOfMap = new TypeToken<Map<String, Object>>()。我从未见过它后面跟着其他代码,比如{}.getType()。这是什么语法?

这是匿名内部类的语法。

{} 是一个对象吗?为什么可以在它上面调用函数?

是的,你可以从中得到一个对象。这就是为什么可以在它上面调用方法的原因。

匿名类在需要单次从类获得特定行为时非常有用。就像下面的例子中,如果你在普通 A 对象上调用 sayHello,它将返回 Hello。但是,对于匿名类的对象,sayHello 方法的行为发生了变化,这次它返回了 Bonjour。

public class SomeClass {
    
    public static void main(String[] args) {
    
        A defaultObj = new A();
        A customObj = new A() {
            @Override
            public String sayHello() {
                return "Bonjour";
            }
        };
    
        System.out.println(defaultObj.sayHello());
        System.out.println(customObj.sayHello());
    
    }
}

class A {
    String sayHello() {
        return "Hello";
    }
}

输出:

Hello
Bonjour

TypeToken 的 Gson 文档还提到了匿名类的原因和用法。在 TypeToken 类中使用匿名类的原因是它用于在运行时检索令牌的类型。否则,由于类型擦除,泛型类型信息在运行时是不可用的。

https://www.javadoc.io/doc/com.google.code.gson/gson/2.6.2/com/google/gson/reflect/TypeToken.html

代表泛型类型 T。目前 Java 还没有提供表示泛型类型的方式,因此该类提供了一种。强制客户端创建该类的子类,从而能够在运行时检索类型信息。例如,要为 List 创建类型文字,可以创建一个空的匿名内部类:

TypeToken<List> list = new TypeToken<List>() {};

英文:

> I usually call a constructor like this: final Type typeOfMap = new
> TypeToken<Map<String, Object>>(). I have never seen it followed by
> other pieces of code such as {}.getType(). What kind of syntax is
> this?

It is a syntax for Anonymous inner classes.

> Is {} an object? Why can you call a function on it?

Yes, you get an object from it. That's why a method can be invoked on it.

Anonymous classes are useful when you need a specific behaviour from a class for a single time. Like in below example, if you invoke sayHello on normal A object, then it will return Hello. But, the behaviour of sayHello method gets changed for object of anonymous class and it returns Bonjour this time.

public class SomeClass {

    public static void main(String[] args) {

        A defaultObj = new A();
        A customObj = new A() {
            @Override
            public String sayHello() {
                return &quot;Bonjour&quot;;
            }
        };

        System.out.println(defaultObj.sayHello());
        System.out.println(customObj.sayHello());

    }
}

class A {
    String sayHello() {
        return &quot;Hello&quot;;
    }
}

Output

Hello
Bonjour

Gson documentation for TypeToken also mentions about the reason and usage of anonymous class. The reason for usage in TypeToken class is that it is used to retrieve the type of token at runtime. As otherwise generic type information is not available at runtime because of type erasure.

https://www.javadoc.io/doc/com.google.code.gson/gson/2.6.2/com/google/gson/reflect/TypeToken.html

> Represents a generic type T. Java doesn't yet provide a way to
> represent generic types, so this class does. Forces clients to create
> a subclass of this class which enables retrieval the type information
> even at runtime. For example, to create a type literal for
> List<String>, you can create an empty anonymous inner class:
>
> TypeToken<List<String>> list = new TypeToken<List<String>>() {};

huangapple
  • 本文由 发表于 2020年9月4日 10:16:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/63733927.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定