File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Java in General and the fly likes Trouble with Class.forName().getInstance() Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Trouble with Class.forName().getInstance()" Watch "Trouble with Class.forName().getInstance()" New topic
Author

Trouble with Class.forName().getInstance()

Mike Curwen
Ranch Hand

Joined: Feb 20, 2001
Posts: 3695

I thought I'd be clever, look where it got me...
I have data that needs to be 'massaged' before my process can use it. So I wanted to make things easy on myself and I tried to figure out a way to enable dynamic, run-time decisions about how to massage the data. Because certain datasets need to be massaged in certain ways.

So my idea was to have an interface "Massager" that contains one method "massage". Then all of my massaging classes will implement this interface. As an added benefit, since they all implement the interface, I can refer to them through an interface variable.


And then my code that tries to generically use this would use nice little mappings and Class.forName() to get an appropriate massager instance...



This compiles, but fails at runtime with a ClassCastException. I can't use the more general instance of 'Object' that getInstance() returns, because of course, Object doesn't have a massage method. I've also tried this scheme with abstract superclasses. This involves replacing my interface with an abstract class. My more specific classes then extend this class, and my variables are not interface type, but the superclass type.

I admit, I'm totally bamboozled why this won't work. Isn't that an advantage of
interfaces? Anyways, has anyone implemented this type of behaviour? What am I doing wrong?
[ March 12, 2003: Message edited by: Mike Curwen ]
Greg Charles
Sheriff

Joined: Oct 01, 2001
Posts: 2851
    
  11

It works OK for me, with the caveat that getInstance() should be newInstance(). The cast worked fine for me and called the "foo" method as expected.
Mike Curwen
Ranch Hand

Joined: Feb 20, 2001
Posts: 3695

well, this is extremely frustrating, and yet gratifying.

I changed *nothing*, but when I switched to my classes directory, I noticed a misplaced class file (I changed a few packages during development). I deleted all classes, recompiled everything, and now it all works as expected.

Thanks.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Trouble with Class.forName().getInstance()