redspider
redspider

Reputation: 133

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 the member to itself.

class TestClass {
    String id;
}

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

Beside the obvious method to rename the id parameter, is there any other way to access it? Thx

Upvotes: 4

Views: 119

Answers (2)

Arpit Aggarwal
Arpit Aggarwal

Reputation: 29276

Offtopic, Java 8 Snippet to achieve the same:

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

Usage:

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());
    }
}

Upvotes: 0

wero
wero

Reputation: 32980

You can avoid the anonymous class

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

or rename the parameter

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

or drop the factory method all together by introducing a constructor parameter:

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

Upvotes: 1

Related Questions