Access parameter from anonymous class

I have a (pedantic) Java question: I want to create an anonymous class in a method and assign a method parameter to a member with the same name. The code below does not work as it assigns a member to itself.

class TestClass {
    String id;
}

TestClass createTestClass(final String id) {
    return new TestClass() {{
        this.id = id; // self assignment of member
    }};
}

Besides the obvious method of renaming the id parameter, is there any other way to access it? thanks

+4
source share
2 answers

You can avoid anonymous class

TestClass createTestClass(final String id) {
     TestClass testClass = new TestClass();
     testClass.id = id;
     return testClass;
} 

or rename option

TestClass createTestClass(final String theId) {
    return new TestClass() {{
        this.id = theId; 
    }};
}

or leave the factory method together by entering the constructor parameter:

class TestClass {
    public TestClass(String id) { this.id = id; }
    String id;
}
+1
source

Offtopic, Java 8Snapshot to achieve the same:

Function<String, TestClass> createTestClass = TestClass::new;

Using:

final class TestClass {
    private final String id;

    public TestClass(String id) {
        this.id = id;
    }

    public String getId() {
        return id;
    }
};

public class AnyClass {
    static Function<String, TestClass> createTestClass = TestClass::new;

    public static void main(String[] args) {
        TestClass testclass = createTestClass.apply("hello");
        System.out.println(testclass.getId());
    }
}
0
source

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


All Articles