megamonium
megamonium

Reputation: 483

Unusual syntax used for object construction

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<Map<String, Object>>() {}.getType();

My questions are:

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

Upvotes: 0

Views: 101

Answers (2)

SKumar
SKumar

Reputation: 2030

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 "Bonjour";
            }
        };

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

    }
}

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

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, you can create an empty anonymous inner class:

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

Upvotes: 0

Delark
Delark

Reputation: 1323

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<Map<String, Object>>() {} The class tiself may look something like this: public abstract class TypeToken<X> ... 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".

Upvotes: 1

Related Questions