Abstract Classes and Reflection in Java

abstract-class, java, reflection

Solution

You can't instantiate anonymous inner classes through newInstance(). Non-static inner classes hold a reference to their container Object, you need that Object to create them.

See Java Tutorial -> Nested Classes

Problem

I have an abstract class which is mostly instantiated as anonymous inner classes, with abstract method implemented there. These instances get passed around, and so at a different place in the code I would like to get a copy of one of these instances, a new instance but with the method implemented the same way. Here is an example of my code: ``` public abstract class AbstractClass { String id; Entity owner; public AbstractClass(String id){ this.id=id; } public Mover(){ id="This is an id"; } abstract void update(); } ``` I instantiate it like this: ``` AbstractClass instance= new AbstractClass("This is a test"){ void update(){ //do stuff } } ``` Later, I want a copy, not a reference, of that instance, where update() does the same stuff, but owner will be a different entity. I've tried to use reflection, (.getClass.newInstance()), but I get a java.lang.InstantiationException. Why doesn't this work and is there a better way to do what I'm doing?

Original source