G
Gary
Hi, I got the following exception when running the codes attached
below:
Exception in thread "main" java.lang.InstantiationException:
IFactory$1
at java.lang.Class.newInstance0(Class.java:281)
at java.lang.Class.newInstance(Class.java:249)
at IFactory.getI(IFactory.java:20)
at IFactory.main(IFactory.java:35)
Is it because Java doesn't support reflection for anonymous inner
class? If so, how can I add dynamic classes? Is it possible?
Thanks in advance.
Gary
import java.util.*;
public class IFactory {
private static HashMap map = new HashMap();
private static IFactory factory = new IFactory();
static {
map.put("A", A.class);
map.put("B", B.class);
}
private IFactory() {}
public static IFactory getInstance() {
return factory;
}
public I getI(String name) throws Exception {
Class c = (Class) map.get(name);
return (I) c.newInstance();
}
public void addI(String name) throws Exception {
I i = new I() {public void print(){System.out.println("C");}};
map.put(name, i.getClass());
}
public static void main(String[] args) throws Exception {
IFactory factory = IFactory.getInstance();
factory.getI("A").print();
factory.addI("C");
factory.getI("C").print();
}
}
abstract class I {
abstract public void print();
}
class A extends I {
public void print() {
System.out.println("A");
}
}
class B extends I {
public void print() {
System.out.println("B");
}
}
below:
Exception in thread "main" java.lang.InstantiationException:
IFactory$1
at java.lang.Class.newInstance0(Class.java:281)
at java.lang.Class.newInstance(Class.java:249)
at IFactory.getI(IFactory.java:20)
at IFactory.main(IFactory.java:35)
Is it because Java doesn't support reflection for anonymous inner
class? If so, how can I add dynamic classes? Is it possible?
Thanks in advance.
Gary
import java.util.*;
public class IFactory {
private static HashMap map = new HashMap();
private static IFactory factory = new IFactory();
static {
map.put("A", A.class);
map.put("B", B.class);
}
private IFactory() {}
public static IFactory getInstance() {
return factory;
}
public I getI(String name) throws Exception {
Class c = (Class) map.get(name);
return (I) c.newInstance();
}
public void addI(String name) throws Exception {
I i = new I() {public void print(){System.out.println("C");}};
map.put(name, i.getClass());
}
public static void main(String[] args) throws Exception {
IFactory factory = IFactory.getInstance();
factory.getI("A").print();
factory.addI("C");
factory.getI("C").print();
}
}
abstract class I {
abstract public void print();
}
class A extends I {
public void print() {
System.out.println("A");
}
}
class B extends I {
public void print() {
System.out.println("B");
}
}