D
D
DarkByte20152017-08-09 12:30:45
Java
DarkByte2015, 2017-08-09 12:30:45

What is going on???

I will show a simplified code from my project. I just have a butchert from him ...
MyModel.java

package com.company;

public class MyModel {
    public String myField;
}

MyView.java
package com.company;

public class MyView {
    public String myField;
}

MyMapper.java
package com.company;

public class MyMapper {
    public static MyView map(MyModel model) {
        return new MyView() {{
           myField = model.myField;
        }};
    }

    public static MyModel map(MyView view) {
        return new MyModel() {{
           myField = view.myField;
        }};
    }
}

Main.java
package com.company;

import static com.company.MyMapper.*;

public class Main {

    public static void main(String[] args) {
        MyView view = new MyView() {{
            myField = "Hello world!";
        }};

        myMethod(map(view));
    }

    public static void myMethod(MyModel model) {
        System.out.println(model.getClass().getName()); // com.company.MyMapper$2
    }
}

The code couldn't be simpler. But, note the output of the application: "com.company.MyMapper$2". What the hell is going on??? Why the hell do I have a model in a method explicitly declared to be of type MyModel that suddenly turns out to be of type MyMapper? What's the magic?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Oparin, 2017-08-09
@DarkByte2015

It is not MyMapper. It is MyMapper$2.
Replace

return new MyModel() {{
           myField = view.myField;
        }};

on the
MyModel myModel = new MyModel();
myModel.myField = view.myField;
return myModel;

and the magic will disappear

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question