Possible Duplicate:
ClassnotFound exception using java reflection
I get exception, java.lang.ClassNotFoundException: SavingAccount, while executing the following code:
public class AccountFactory {
public void getAccount()
{
IAccount account;
account = null;
try
{
account = (IAccount)Class.forName("SavingAccount").newInstance();
account.Deposit(500);
}
catch(Exception e)
{
System.out.println(e.toString());
}
}
}
What could be the possible reasons causing the error?
this is my saving account code:
public class SavingAccount implements IAccount {
int money;
SavingAccount()
{
money =0;
}
public void WithDraw(int m)
{
money--;
}
public void Deposit(int m)
{
money++;
System.out.println(money);
}
}
The classloader cannot find the SavingsAccount class. You also need to use the fully qualified name for the class when using the Class.forName method as specified in the Java API. A fully qualified class name includes the class name prefixed by the package structure. If your AccountFactory class is always going to create a class of type SavingsAccount every time, I would recommend not even having an AccountFactory class and instead just using:
If the posted code is just a snapshot of your class and you do intend to return different types implementing the IAccount interface from your factory you will want to change the getAccount method signature so that it returns an IAccount and not void. You must then use the return statement to return an object that implements the IAccount interface. Such as: