How to create objects at runtime?

I need to make several different class objects at runtime. This number is also determined at runtime.

Something like if we get int no_o_objects = 10 at runtime. Then I need to instantiate the class 10 times.
Thanks

+3
source share
5 answers

Read more about Arrays in the Java Tutorial .

class Spam {
  public static void main(String[] args) {

    int n = Integer.valueOf(args[0]);

    // Declare an array:
    Foo[] myArray;

    // Create an array:
    myArray = new Foo[n];

    // Foo[0] through Foo[n - 1] are now references to Foo objects, initially null.

    // Populate the array:
    for (int i = 0; i < n; i++) {
      myArray[i] = new Foo();
    }

  }
}
+9
source

Objects in Java are created only in Runtime .

Try the following:

Scanner im=new Scanner(System.in);
int n=im.nextInt();

AnyObject s[]=new AnyObject[n];
for(int i=0;i<n;++i)
{

     s[i]=new AnyObject(); // Create Object
}
0
source

.

public AClass[] foo(int n){
    AClass[] arr = new AClass[n];
    for(int i=0; i<n; i++){
         arr[i] = new AClass();
    }
    return arr;
}
0

List, .

MyClass[] classes = new MyClass[n];

n new MyClass() classes[i].

0

This is a tricky question, and the perfect solution uses java reflection. You can create objects and throw them as needed at runtime. Also with this technology you can decide the number of instances of objects.

These are good links:

Reference1

Reference2

-1
source

Source: https://habr.com/ru/post/1726211/


All Articles