javareflectionplayframeworkclassloaderdynamic-class-loaders

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.


Solution

  • With Javassist try

    private static ClassPool pool = ClassPool.getDefault();
    private static RandomString rs = new RandomString();
    
    public static Object getNewClassObject() {
        String name = rs.nextString();
        Object obj = null;
    
        try {
            obj = pool.makeClass(name).toClass().newInstance();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    
        return obj;
    }
    

    RandomString is from here: How to generate a random alpha-numeric string?

    pom.xml

    <dependency>
        <groupId>org.javassist</groupId>
        <artifactId>javassist</artifactId>
        <version>3.27.0-GA</version>
    </dependency>