简体   繁体   English

函数调用后的花括号是什么?

[英]What are curly braces after function call for?

In the following code, what does Type type mean, and what are the curly brackets are used for? 在下面的代码中, Type type含义是什么,大括号用于什么?

Type type = new TypeToken<List<String>>(){}.getType();
List<String> list = converter.fromJson(jsonStringArray, type ); 

Type is a class. Type是一个类。

new TypeToken<List<String>>() {
}.getType();

Is creating an anonymous inner class and invoking getType() on the object created. 创建一个匿名内部类并在创建的对象上调用getType()

That's not after a function call, but after a constructor call. 这不是在函数调用之后,而是在构造函数调用之后。 The line 这条线

Type type = new TypeToken<List<String>>(){}.getType();

is creating an instance of an anonymous subclass of TypeToken , and then calling its getType() method. 正在创建一个TypeToken的匿名子类的TypeToken ,然后调用它的getType()方法。 You could do the same in two lines: 你可以用两行来做同样的事情:

TypeToken<List<String>> typeToken = new TypeToken<List<String>>(){};
Type type = typeToken.getType();

The Java Tutorial Anonymous Subclasses has more examples of this. Java Tutorial Anonymous Subclasses有更多这方面的例子。 This is a somewhat peculiar usage, since no methods are being overridden, and no instance initialization block is being used. 这是一种有点特殊的用法,因为没有覆盖任何方法,也没有使用实例初始化块。 (See Initializing Fields for more about instance initialization blocks.) (有关实例初始化块的更多信息,请参阅初始化字段 。)

The curly brackets are the anonymous class constructor and are use after a constructor call. 大括号是匿名类构造函数,在构造函数调用后使用。 Inside you can override or create a method. 在里面你可以覆盖或创建一个方法。

Example: 例:

    private static class Foo {

    public int baz() {
        return 0;
    }
}

public static void main(final String[] args) {
    final Foo foo = new Foo() {
        @Override
        public int baz() {
            return 1;
        }
    };

    System.out.println(foo.baz());
}

Output: 输出:

1

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

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