Reflection Question

T

Tim

Is there a way to use reflection on an interface to find out what
classes implement it?

I am trying to create a concrete implementation of an interface using
Class.newInstance(), but I only have the Class object for the
interface at runtime.

I'm guessing that I can only look up the inheritance hierarchy (i.e.
getSuperClass(), getInterfaces(), etc.) and not down, but I figure
it's worth asking.

Any help would be appreciated. Thanks in advance.

Tim
 
M

Michael Borgwardt

Tim said:
Is there a way to use reflection on an interface to find out what
classes implement it?

No, because the JVM can not, at any time, know all classes it potentially
has access to. The classloader mechanism is so flexible that the JVM
does not know whether a certain class exists (and what its properties
are) until it has explicitly tried to load that class via its name.
There are classlaoders that load classes via HTTP from the internet
(and don't know whether the class exists until they get a response
from the webserver), you can even write classloaders that generate
classes on the fly according to whatever rules you might conceive.
And any of those classes might or might not implement your interface.
 
A

Adam Maass

Michael Borgwardt said:
No, because the JVM can not, at any time, know all classes it potentially
has access to. The classloader mechanism is so flexible that the JVM
does not know whether a certain class exists (and what its properties
are) until it has explicitly tried to load that class via its name.
There are classlaoders that load classes via HTTP from the internet
(and don't know whether the class exists until they get a response
from the webserver), you can even write classloaders that generate
classes on the fly according to whatever rules you might conceive.
And any of those classes might or might not implement your interface.

Though, if you know precisely where the VM might load classes from, and have
read access to those locations to get a listing of classes, you could
brute-force load classes looking for those that implement your interface.
Ugly at best and not guaranteed to work in all situations (as under the more
esoteric situations above).

-- Adam Maass
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,578
Members
45,052
Latest member
LucyCarper

Latest Threads

Top