anonymous inner class reflection question

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");
}
}
 
G

Gordon Beaton

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?

Constructors to inner classes have a hidden first argument that you
need to provide when you use reflection. Pass an instance of the outer
class.

Use "javap -s" to confirm this.

/gordon
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top