I have 50 classes. I need create 50 objects in main class for use these classes. Classes name Chapter1,Chapter2...Chapter50. How create create it just with loops in java?
I don't know. I have no idea. I cant find information about it in Net.
I have 50 classes. I need create 50 objects in main class for use these classes. Classes name Chapter1,Chapter2...Chapter50. How create create it just with loops in java?
I don't know. I have no idea. I cant find information about it in Net.
There are several solutions. The first solution, as already suggested in the comments, is to use reflection.
Reflection is a feature in the Java programming language. It allows an executing Java program to examine or "introspect" upon itself, and manipulate the internal properties of the program. For example, it's possible for a Java class to obtain the names of all its members and display them.
Source: oracle.com
With reflection, you can create an instance of any class defined in a program by knowing its full name. The fully qualified name includes the package name and the class name, for example package1.package2.ClassName
For this we can use this code:
Class<?> clazz = Class.forName(className);
Constructor<?> ctor = clazz.getConstructor();
Object object = ctor.newInstance();
To keep the example simple, I'm providing a code snippet that assumes that a parameterless constructor is available in all Chapter classes.
In addition, you need to save the created objects somewhere, and for these purposes you can use the ArrayList<ClassType>
class.
Finally, care must be taken that all created objects have a common type. To do this, you can create an IChapter
interface and implement it in each class Chapter-1 ... Chapter-n.
File IChapter
:
public interface IChapter { }
Example of file IChapter-n
:
public class Chapter1 implements IChapter {
public Chapter1() {
//Some action
}
}
Method main
:
public static void main(String[] args) {
List<IChapter> objects = new ArrayList<>(); //Create a list of IChapter objects
int classQuantity = 3; //Specify the number of classes
for (int i = 1; i <= classQuantity; ++i) {
/*
* We specify the full name of the class with the package,
* in my case I did not create a separate package.
* The class number is taken from the loop
*/
String fullClassName = "Chapter" + i;
try {
//Create an instance of the class
Class<?> clazz = Class.forName(fullClassName);
IChapter object = (IChapter) clazz.getConstructor().newInstance();
//Adding the created object to the list
objects.add(object);
} catch (InstantiationException | IllegalAccessException | IllegalArgumentException
| InvocationTargetException | NoSuchMethodException | SecurityException
| ClassNotFoundException e) {
//We catch possible errors and print them to the console
e.printStackTrace();
}
}
//Print to the console the names of all created objects from the list
for (IChapter chapter : objects) System.out.println(chapter.getClass().getName());
}
In my case, the console output will be like this:
Chapter1
Chapter2
Chapter3
As for the shortcomings, the most critical shortcoming is the speed of reflection. I would say that wherever you have to write an average amount of code without reflection and a few lines of code with reflection, you should choose the first option.
It is possible to optimize this code to not create instances via reflection. This will require static initializers, but we still have to load the class. I don't know how much performance can be won this way, so if anyone has corrections, I'll be glad to hear in the comments.
Example of file IChapter-n
:
public class Chapter1 implements IChapter {
//We create an instance in the static class initializer and add it to the Main class
static {
Main.registerObject(new Chapter1());
}
}
Class Main
:
public class Main {
private static List<IChapter> objects = new ArrayList<>();
public static void registerObject(IChapter chapter) {
objects.add(chapter);
}
public static void main(String[] args) {
int classQuantity = 3;
for (int i = 1; i <= classQuantity; ++i) {
String fullClassName = "Chapter" + i;
try {
//Load class
Class.forName(fullClassName);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
for (IChapter chapter : objects) {
System.out.println(chapter.getClass().getName());
}
}
}
Having a class name and not having the desire to refer to this class directly, you can create a class using reflection, for example. But doing this is not recommended. Therefore, the most correct way would be to make a separate method that will create instances of the necessary classes. For example:
public static void createObjects() {
objects.add(new Chapter1());
objects.add(new Chapter2());
//ect...
}
Then you just need to call this method in the main method:
public static void main(String[] args) {
createObjects();
}
public class Main {
public static void main(String[] args) {
// Create an array to store the 50 objects
Object[] chapterObjects = new Object[50];
// Create objects for each chapter using a loop
for (int i = 0; i < 50; i++) {
chapterObjects[i] = createChapterObject(i + 1);
}
// Use the objects as needed
// ...
}
// Helper method to create an object for a specific chapter
private static Object createChapterObject(int chapterNumber) {
switch (chapterNumber) {
case 1:
return new Chapter1();
case 2:
return new Chapter2();
// Add cases for all 50 chapters
case 50:
return new Chapter50();
default:
throw new IllegalArgumentException("Invalid chapter number: " + chapterNumber);
}
}
}
In this example, an array chapterObjects is created to store the 50 objects. The for loop is used to iterate from 1 to 50 and call the createChapterObject method to create an object for each chapter. The createChapterObject method takes the chapter number as an argument and uses a switch statement to return a new object for the corresponding class. Finally, the objects are stored in the chapterObjects array and can be used as needed.