简体   繁体   中英

Java - Referencing an object with a variable

I am trying to instantiate an object from within an if statement, basically an object when the user wants to create one. If the same code is being executed (with different arguments) then the reference to the object will be the same so…

Can you reference the object from a different variable, for example a unique id that is created in the constructor for the object?

    Test test1 = null;
    if (run == true){
       test1 = new Test(argument1);
       test1 = test1.id;
       }

I am inexperienced, but basically want a variable from the object to then point at that object, so it does not get overwritten when a new object is instantiated from the code being executed again.

Thanks

I get the sense that you're overcompensating for a scenario which wouldn't normally occur in Java.

To answer the question directly: you wouldn't be able to use the ID of an object to refer to the object later unless you had a data structure (like a Map<Integer, Test> ) keeping track of those instances.

In the scenario you illustrate, the only way that test1 is not null is if your test condition passes. Outside of that, it stands a chance of being null and causing runtime issues later. Further, the reassignment to test1 would fail if test1.id is not also an instance of Test .

You cannot dynamically name variables in Java. May i suggest creating a List of Test variables? Every time the loop executes, add the variable to the List . This way you have a reference to all the objects that have been created.

The instance won't be overwritten when you create a new instance, only your reference to the object will be overwritten. If you want to manage multiple instances of the object, you'll have to keep track of your references to them. You could keep an array of object references or collection of object references in your build function. Alternately, you could return the object reference to the caller and keep track of it there.

You probably want to use something like an array here

int count = 0;
    Test[] tests = new Test[10];

    if(run == true){
        tests[count] = new Solution(argument1);
        count++;
    }

In this case we are making slots for 10 objects, really any number can go inside where that 10 is. It also might be a good idea to use something like an ArrayList if your not sure how many objects you need to make.

To get an element from the array and use the object we can simply just use the name of the array followed by the spot in the array where it is located.

tests[0].someMethod() //will call the method on the object at index 0

Remember arrays start counting at zero so if you want the 2nd element you have to ask for the element at index 1.

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