views:

390

answers:

2

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

  • Should you reuse that interface or create a new one each time?
  • The proxy class is effectively a new instance of type java.lang.reflect.Proxy, which might cause implications depending on the use case.

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.

A: 

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.

Yishai
+2  A: 

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).

Esko Luontola
+1 for the second paragraph.
Stephen C