Question

Is it possible to compose new class at runtime in Java?

What are the means for that? Refection? Compiler API?

I can do

package tests;

public class TryReflection02 {

    interface A {

    }

    public static void main(String[] args) {

        Object o = new A() {};

        System.out.println( o.toString() );

        o = A.class.newInstance() // exception

    }

}

Can I do the same having A.class value?

Was it helpful?

Solution

No, you can't. A is an interface, and only classes can be instantiated.

What you can do is to use a library/helper that uses some trickery to create a class that implements the interface and instantiates that. The JDK's Proxy class contains static methods to do just that. There are also tools that can do it which are custom-geared for test-related use cases: mockito, for instance.

These tools do exactly what you hint at in this question's title: rather than instantiating the interface, they generate a new class that implements the interface, and then instantiate that class.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top