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...

1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

In this case I think "prototype instance" refers to the instance sent as first parameter to introduce(), rather than in some prototype inheritence sense.
If there won't be other answers, I guess, it impossible then for all three parts of my question...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.