简体   繁体   English

从匿名类访问参数

[英]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. 我有一个(迂腐的)Java问题:我想在方法中创建一个匿名类,并为具有相同名称的成员分配一个方法参数。 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? 除了重命名id参数的明显方法之外,还有其他方法可以访问它吗? 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: Offtopic, Java 8 Snippet实现相同:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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