What are the braces after calling the function?

In the following code, what does Type type mean, and what braces are used for?

 Type type = new TypeToken<List<String>>(){}.getType(); List<String> list = converter.fromJson(jsonStringArray, type ); 
+6
source share
3 answers

Type - class.

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

Creates an anonymous inner class and calls getType() on the created object.

+5
source

This is not after a function call, but after a constructor call. Line

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

creates an instance of the anonymous subclass of TypeToken , and then calls its getType() method. You can do the same in two lines:

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

The Java Tutorial Anonymous Subclasses contains more examples. This is a somewhat peculiar use, since no methods are overridden, and the instance initialization block is not used. (For more information about blocking instance initialization, see Initializing Fields .)

+4
source

Curly braces are an anonymous class constructor and are used after calling the constructor. 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 
+1
source

Source: https://habr.com/ru/post/954451/


All Articles