简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM