Reputation: 109
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 );
Upvotes: 10
Views: 2408
Reputation: 3271
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
Upvotes: 1
Reputation: 62583
Type
is a class.
new TypeToken<List<String>>() {
}.getType();
Is creating an anonymous inner class and invoking getType()
on the object created.
Upvotes: 8
Reputation: 85823
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.)
Upvotes: 8