在Java中,是否可以动态创建仅给定父类实例的匿名子类实例? [英] In Java is it possible to dynamically create anonymous subclass instance given only instance of parent class?

查看:403
本文介绍了在Java中,是否可以动态创建仅给定父类实例的匿名子类实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中是否可以动态创建只给出父类实例的匿名子类实例?

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

我试图实现的模式代码如下所示: / p>

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());
}

实际上还有2个关于此代码的要求问题:

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

(2)不仅创建子类实例,还将原型实例重新分配给新创建的实例(代码中的第二个断言)。

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

(3)将子类引入某个特定的接口。

(3) Introduce the subclass to some specific interface.

我怀疑这是可能的,但我是Java的新手,所以...

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

推荐答案

如果您是java新手,您必须问自己为什么需要此功能。如果你只描述你想要解决的问题,肯定会有更好的解决方案。

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不使用原型继承。

Java does not employ prototypical inheritance.

这篇关于在Java中,是否可以动态创建仅给定父类实例的匿名子类实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆