-3

I could not understand following code snippet:

Unirest.setObjectMapper(new ObjectMapper() {
    private com.fasterxml.jackson.databind.ObjectMapper jacksonObjectMapper
            = new com.fasterxml.jackson.databind.ObjectMapper();

    public <T> T readValue(String value, Class<T> valueType) {
        try {
            return jacksonObjectMapper.readValue(value, valueType);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public String writeValue(Object value) {
        try {
            return jacksonObjectMapper.writeValueAsString(value);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }
});

ObjectMapper is an interface, how come I can define with new keyword like is? It looks like java 8 feature, right?

Tunaki
  • 132,869
  • 46
  • 340
  • 423
softshipper
  • 32,463
  • 51
  • 192
  • 400

2 Answers2

2

This a very common practice in Java and what you are seeing is called anonymous classes. The same code can be replaced by following:

private class ObjectMapperChild extends ObjectMapper
{
private com.fasterxml.jackson.databind.ObjectMapper jacksonObjectMapper
            = new com.fasterxml.jackson.databind.ObjectMapper();

    public <T> T readValue(String value, Class<T> valueType) {
        try {
            return jacksonObjectMapper.readValue(value, valueType);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public String writeValue(Object value) {
        try {
            return jacksonObjectMapper.writeValueAsString(value);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }
}

ObjectmapperChild objMapperChild = new ObjectMapperChild();
Unirest.setObjectMapper(objMapperChild);
java_doctor_101
  • 3,287
  • 4
  • 46
  • 78
1

It's a anonymous class. When you, for example, don't want to create new class file with its declaration because you will use this class only in that one place of your code, then you can do it like this.

In Java 1.8 with introduction of Functional interfaces (interfaces with only one method) you can declare such anonymous classes with use of Lambda expressions. For example when you want to filter a list:

(Person p) -> p.getGender() == Person.Sex.MALE

is the same as

 new CheckPerson() {
     public boolean test(Person p) {
         return p.getGender() == Person.Sex.MALE;
     }
 }

when

interface CheckPerson {
    boolean test(Person p);
}

You can find more regarding lambdas here - https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html.

Bananan
  • 613
  • 5
  • 19