开发者

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

开发者 https://www.devze.com 2023-02-12 19:04 出处:网络
In Java is it possible t开发者_StackOverflow社区o dynamically create anonymous subclass instance given only instance of parent class?

In Java is it possible t开发者_StackOverflow社区o 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...


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消