vendredi 11 septembre 2020

Create Object of new different Class every time

I want to create objects of a new class(different name specifically) continuously.

public static void main(String args[]) {
    while (true) {
        Object obj = getNewClassObject();
        System.out.println(obj.getClass.getName());
    }
}

public static Object getNewClassObject() {
    // some code
}

The task is what should we write in the method so it returns an Object of different class every time and the program prints different class name in each line.

I have tried using Anonymous class, Inner class, lambdas etc.. but they all return the same class name. My current "lame" solution is creating new class files inside a play application(has reloading ability) and then using reflection lib(or just java code) to load class and get the object of the new class.

But it takes a lot of memory also reflection method getSubTypeOf() takes a lot of time ~100 secs and after some time I get OutOfMemoryError. I hope there is a better way to do it. I am thinking something like unloading or releasing class metadata to free up memory.





Aucun commentaire:

Enregistrer un commentaire