3

In Java is it possible to dynamically create anonymous subclass instance given only instance of parent class?

The pattern code I'm trying to implement looks like this:

public interface IStringCarier { public String getStr(); }

public static IStringCarier introduce(Object victim, final String str) {
   // question subject
}

public class AAA { }

public static void main() {
    AAA aaa = new AAA();

    assert !(aaa instanceof IStringCarier);

    IStringCarier bbb = introduce(aaa, "HelloWorld");

    assert aaa == bbb;
    assert "HelloWorld".equals(bbb.getStr());
}

There're actually 2 more requirements-questions regarding this code:

(2) Not just create subclass instance, but also reassign prototype instance to the newly created instance (2nd assert in the code).

(3) Introduce the subclass to some specific interface.

I doubt this is possible, but I'm novice with Java, so...

Andrey
  • 333
  • 3
  • 5
  • 16
  • Possible duplicate of [In Java, can I create an instance of an anonymous subclass from a Class object?](http://stackoverflow.com/questions/1306474/in-java-can-i-create-an-instance-of-an-anonymous-subclass-from-a-class-object) – jpaugh Mar 24 '16 at 13:52

1 Answers1

3

If you are new to java, you must ask yourself why you need this functionality. Most certainly there will exist a better solution would you only describe what problem you're trying to solve.

The only approach you have (except for rewriting the bytecode) is to use Dynamic Proxies, as they are capable of implementing an interface at runtime. But using them the way you suggest wouldn't really make much sence.

Not just create subclass instance, but also reassign prototype instance to the newly created instance

Java does not employ prototypical inheritance.

Johan Sjöberg
  • 47,929
  • 21
  • 130
  • 148
  • In this case I think "prototype instance" refers to the instance sent as first parameter to introduce(), rather than in some prototype inheritence sense. – johusman Feb 20 '11 at 17:50
  • If there won't be other answers, I guess, it impossible then for all three parts of my question... – Andrey Feb 20 '11 at 20:04