Link to home
Start Free TrialLog in
Avatar of ericworldz
ericworldz

asked on

ClassCastException Error

I get the ClassCastException for the line below:

String settingsClass = config.getInitParameter("SettingsClass");
                  
Settings settings = (Settings) Class.forName(settingsClass).newInstance(); //<-- this is where the exception error occurs

Thanks for the help!
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Split those bits up and test it.
The class defined by "settingsClass" does not extend or implement "Settings"

Try

System.out.println( settingsClass ) ;

before you do the Class.forName

I reckon it's "null"
The nature of the exception indicates that the forName method is picking up a class, then newInstance is creating an instance of it, but it isn't a class of type Settings, so when it tries to cast it to a class of that type, it throws an exception.

I'm guessing that you are expecting it to be a class of type Settings. If so, perhaps you could print out the string you are getting from the getInitParameter call (System.out.println("class name: "+settingsClass);), and post the code (at least the class definition and the constructor) of the class you are trying to load.
The three musketeers strike again  :)
>>I reckon it's "null"

So do I
Avatar of ericworldz
ericworldz

ASKER

I try to print out the settingsClass and it's not null.
It returns settingsClass=com.goals.Site, so I guess when I try to cast it to Settings it gives me the ClassExceptionError.

Below is the code for the Settings class:
public interface Settings {
public Site getSite(Hashtable initParams) throws Exception;      
}

So what is the way to get around this?
Thanks!
package com.goals ;

public class Site implements Settings
make sure it implements "Settings" :-)
T's always a good idea to type-check anyway

Object o = Class.forName(settingsClass).newInstance();
if (o instanceof Settings) {
     Settings s = (Settings)o;
}

else {
    log.fatal( o + " IS NOT A SETTINGS OBJECT!" ) ;
}
It is implementing Settings
ASKER CERTIFIED SOLUTION
Avatar of TimYates
TimYates
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
>>does "Site" have an empty constructor?

Must have, or couldn't be non-null ;-) (according to eric)
Please, for the benefit of others, explain what the solution to the problem was eric