checking class type alternative to instanceof

T

Timasmith

Hi,

Can I check if a class is an implementation of an interface by name
without instantiating it?

So I can do this:

if (Class.forName("com.company.package.myclass").newInstance()
instanceof MyInterface) {
// class implements interface
}

but it seems create an instance of it by reflection is suboptimal.

Can I do the same thing without calling newInstance()?

thanks
 
T

Thomas Hawtin

Timasmith said:
if (Class.forName("com.company.package.myclass").newInstance()
instanceof MyInterface) {
// class implements interface
}

but it seems create an instance of it by reflection is suboptimal.

Can I do the same thing without calling newInstance()?

Class.isAssignableFrom

I believe you can also get away without initialising the class with
Class.forName(String,false,ClassLoader).

Tom Hawtin
 
E

Eric Sosman

Timasmith wrote On 11/13/06 16:56,:
Hi,

Can I check if a class is an implementation of an interface by name
without instantiating it?

So I can do this:

if (Class.forName("com.company.package.myclass").newInstance()
instanceof MyInterface) {
// class implements interface
}

but it seems create an instance of it by reflection is suboptimal.

Can I do the same thing without calling newInstance()?

You could use getInterfaces() on the Class object and rummage
through the array it returns.

I'm worried about your use of the word "suboptimal," though.
If you're making so many of these inquiries that optimality is
a concern, you're probably making too many. What is it about
the design that requires you to do this so often?
 
T

Timasmith

You could use getInterfaces() on the Class object and rummage
through the array it returns.

I'm worried about your use of the word "suboptimal," though.
If you're making so many of these inquiries that optimality is
a concern, you're probably making too many. What is it about
the design that requires you to do this so often?

It is not so much that I do it so often in the code, I just do it
somewhere which is called a large number of times and I try to avoid
extra object creation where feasible.
 

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

Forum statistics

Threads
473,768
Messages
2,569,575
Members
45,051
Latest member
CarleyMcCr

Latest Threads

Top