Dims
Dims

Reputation: 51259

How to dynamically create new class implementing some interface and instantiate it?

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?

Upvotes: 1

Views: 1783

Answers (1)

yshavit
yshavit

Reputation: 43456

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.

Upvotes: 2

Related Questions