I declared an Interface like the following
public interface One {
void setNo(int no);
}
Then I have a class to implement the interface
public class Two implements One{
private int no;
@Override
public void setNo(int no){
this.no = no;
}
}
I will have a lot of classes to implement the interface and then I want to create the corresponding Object according to user input.
Let's say we have the classes Three, Four, Five described as the Two class.
The user picks to create the class Three. So I try to do something like the following
One base;
Class c = Class.forName("Three");
base = (One) c.newInstance();
base.setNo(5);
the call to base.setNo() fails. Am I doing this right?
Error
java.lang.ClassNotFoundException: Three
at java.net.URLClassLoader$1.run(URLClassLoader.java:372)
at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:360)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:260)
at com.company.Main.main(Main.java:33)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)
setNois package private, which means you can't access it from a class that's not in the same package.