In Java, is it possible to dynamically create an anonymous instance of a subclass specified only by an instance of the parent class?

In Java, is it possible to dynamically create an anonymous instance of a subclass specified only by an instance of the parent class?

The code for the template I'm trying to implement is as follows:

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 are actually 2 more requirements - questions regarding this code:

(2) Not just creating an instance of the subclass, but also reassigning the prototype instance for the newly created instance (2nd state in the code).

(3) Introduce a subclass into a specific interface.

I doubt it is possible, but I am new to Java, so ...

+3
source share
1 answer

If you are new to java, you should ask yourself why you need this functionality. Most likely, there will be a better solution, you would only describe what problem you are trying to solve.

( -) Dynamic Proxies, , , , .

,

Java .

+3

Source: https://habr.com/ru/post/1793411/


All Articles