Java编程错误按引用传递

时间:2016-03-30 06:22:33

标签: java pass-by-reference

我有一个java应用程序,其中有一个对象引用" Validate.Options"作为参数传递给函数" ValidateResult(Validate.Options选项)"并且该函数被称为迭代。在此功能内,基于特定条件的属性" enableProcessing"传递的对象的更改,在下一次迭代时不会重置。我该如何重置这个属性?

以下是示例代码。

public interface Validate 
{
    public List validate();


    public class Options implements Serializable
    {
        public String name;
        public boolean enableProcessing = true;
        public Options(String name)
        {
            this.name = name;
        }
    }
}


public class Coder 
{
    public String name;
    public int age;
    public Coder(String name, int age)
    {
        this.name = name;
        this.age = age;
    }

    public void ValidateResult(Validate.Options option)
    {
        if(option.name.equals(this.name) && option.enableProcessing)
        {
            option.enableProcessing = false;
            //
            //business logic and function call
            //
        }
    }

    public static void main(String[] args) 
    {
        Validate.Options options = new Validate.Options("Test");
        List<Coder> coders = new ArrayList<Coder>();

        Coder coder = new Coder("Test", 28);
        Coder coder1 = new Coder("XYZ", 18);
        Coder coder2 = new Coder("Test", 16);       

        coders.add(coder);
        coders.add(coder1);
        coders.add(coder2);

        for(Coder co : coders)
        {
            co.ValidateResult(options);
        }
    }
}

2 个答案:

答案 0 :(得分:2)

如果我理解了这个问题 - 在for循环中,只需添加一行代码即可重置公共Validate.Options.enableProcessing字段的值

for(Coder co : coders)
    {
        //reset options object for the next iteration
        options.enableProcessing = true;
        co.ValidateResult(options);
    }

答案 1 :(得分:1)

如果您不希望更改选项不可变

public class Options implements Serializable
{
    public final String name; // final prevents changes
    public final boolean enableProcessing = true; // final prevents changes
    public Options(String name)
    {
        this.name = name;
    }
}

本地使用enableProcessing将其值复制到本地变量

public void ValidateResult(Validate.Options option)
{
    boolean enableProcessing = option.enableProcessing; // create local copy
    if(option.name.equals(this.name) && enableProcessing) // use local copy
    {
        enableProcessing = false; // only change local copy
        //
        //business logic and function call
        //
    }
}

或者为每个循环创建新的,新的选项

public static void main(String[] args) 
{
    List<Coder> coders = Arrays. asList(
        new Coder("Test", 28), 
        new Coder("XYZ", 18), 
        new Coder("Test", 16)
   );

   for(Coder co : coders)
   {
        Validate.Options options = new Validate.Options("Test"); // fresh options for each iteration
        co.ValidateResult(options);
    }
}