代码之家  ›  专栏  ›  技术社区  ›  João Pereira

为什么我可以更改类成员,但不能更改类变量甚至原语值[重复]

  •  -3
  • João Pereira  · 技术社区  · 6 年前

    public class Example{
        int y = 2;
        String z = "textExample";
    }
    

    int .

    想象一下另一个类中的这个函数:

    public class newClass {
    
    protected void doActivate() {
        ItemCreation model = new Itemcreation(); //A class with visible moving parts
        Example ex = new Example();
        int i = 2;
    
        model.getSourceProperty().addListener((o, oldVal, newVal) -> {
               //do stuff
               ex.z = "sss"; //THIS I CAN DO and Works
    
    
               Example exTmp = new Example();
               ex = exTmp; //This complains with message: Local variable ex defined in an enclosing scope must be final or effectively final
    
              i= 4;//This also complains with message: Local variable i defined in an enclosing scope must be final or effectively final
    
        });
    }
    

    Java语言有一个特性,在这个特性中,从(匿名的)内部类访问的局部变量必须是(有效的)final” . 但如果是这样的话,为什么我可以改变 Example 班级,哪个不是期末考试?

    1 回复  |  直到 6 年前
        1
  •  0
  •   Jan S.    6 年前

    您需要一个最终标记的对象包装器。

    签出提供所需功能的原子包: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/package-summary.html

    protected void doActivate() {
        ItemCreation model = new Itemcreation(); //A class with visible moving parts
        final AtomicReference<Example> ex = new AtomicReference<>(new Example());
        final AtomicInteger i = new AtomicInteger(2);
    
        model.getSourceProperty().addListener((o, oldVal, newVal) -> {
            ex.get().z = "sss";
            Example exTmp = new Example();
            ex.set(exTmp);
            i.set(4);
        });
    }