简体   繁体   中英

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 = new TypeToken<List<String>>(){}.getType();
List<String> list = converter.fromJson(jsonStringArray, type ); 

Type is a class.

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

Is creating an anonymous inner class and invoking getType() on the object created.

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. 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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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