qnoid
qnoid

Reputation: 2376

How to create an interface at Runtime

Assuming I have a class like

public class FooImpl
{
    public void bar(){};
}

Is there a way to create its interface at runtime?

e.g.

public interface Foo
{
    public void bar();
}

I have been looking into Javasssist and the truth is it's reflection that I'm interested in using the interface for (as Esko Luontola and Yishai stated)

So I want an interface that specifies a subset of the original class' methods to make a proxy from.

I came to realize there are more things to be concerned about like

The last point made me wonder on how some frameworks manage to handle this, do they deep copy the object? do they encapsulate the proxy inside the original instance?

So maybe it's just easier (though maybe not as elegant) to require for the client code to create the interface for the class.

Upvotes: 5

Views: 7403

Answers (2)

Esko Luontola
Esko Luontola

Reputation: 73655

You can do it with some bytecode manipulation/generation during class loading, for example using ASM, Javassist or similar, maybe also AspectJ.

The important question is, why would you need to do that? No normal code can use the class through its interface, because the interface does not exist at compile time. You would either need to generate the code that uses the interface or use reflection - but in that case you might as well use the original class. And for the interface to be useful, you should probably also modify the original class so that it implements the generated interface (this can be done with the libraries I mentioned).

Upvotes: 3

Yishai
Yishai

Reputation: 91931

You can look at something like Javassist to create the class. You would go over the class with Class.getMethods() and have to implement the bytecode at runtime for the interface, and then use the Proxy class to bridge the interface and implementation.

Upvotes: 1

Related Questions