Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / November 2006

Tip: Looking for answers? Try searching our database.

checking class type alternative to instanceof

Thread view: 
Timasmith - 13 Nov 2006 21:56 GMT
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
Thomas Hawtin - 13 Nov 2006 22:28 GMT
> if (Class.forName("com.company.package.myclass").newInstance()
> instanceof MyInterface) {
[quoted text clipped - 4 lines]
>
> 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
Eric Sosman - 13 Nov 2006 22:43 GMT
Timasmith wrote On 11/13/06 16:56,:
> Hi,
>
[quoted text clipped - 11 lines]
>
> 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?

Signature

Eric.Sosman@sun.com

Timasmith - 13 Nov 2006 22:48 GMT
>     You could use getInterfaces() on the Class object and rummage
> through the array it returns.
[quoted text clipped - 6 lines]
> --
> Eric.Sosman@sun.com

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.


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.