0

假设我有一组要扩展的类,因为它们具有不同的属性,我将在回调函数中使用(即将到来):

class ExtendMe1 //
class ExtendMe2 //

我想写一个以编程方式扩展它的新类。有没有办法做这样的事情:

ExtenderTemplate(
    <ExtendMe1>, // Class to extend
    <AClassToExtendWith>, // New class name that i'm extending for
    CallbackFunction() // A function that can be run locally inside our new class
);

假设 ExtenderTemplate 方法看起来像这样:

void ExtenderTemplate( <Ext>, <NewClass> )
{
    CreateClass( <NewClass ).Extends( <Ext> ).Run( CallbackFunction );
}

有没有办法在 Java 中做到这一点?

生成的类将以编程方式构建,但看起来像这样:

public class AClassToExtendWith extends ExtendMe1
{
    public AClassToExtendWith()
    {
        CallbackFunction();
    }
    public void CallbackFunction()
    {
        // accesses something that belongs to ExtendMe1
    }
}

语境

我们有一组 ui 控件,我们必须用我们自己的类进行扩展,在其中做一些常规的废话,然后实际做一些事情来扩展 ui 控件(希望可以通过回调函数来完成)。如果我们可以将它打包到某个模板方法中,那将是非常棒的,最后你只有这 3 个参数.. 你在扩展哪个 ui 控件,你想要调用什么类(所以我们可以在我们的视图中调用) 最后你将要对 ui 控件进行哪些更改(回调函数)

进一步阐明我们的团队可能如何使用此功能

  • 所以我想扩展其他人制作的 UI 控件。我知道它叫什么。
  • 我需要在我的代码中以某种方式调用它,所以我需要给它一个好听的新名称......我也需要这样做,因为我想为它编写更多功能。
  • 我想修改 UI 控件,以便它使用我的功能。

我最终可能会用类似的东西来调用它(这必须是伪的)

ExtenderTemplate( "NewUIControl", "UIControl_Table", {
    UiControlRender.text = "New stuff added by accessing the extended method";
});

否则我将不得不这样做:

public class NewUIControl extends UIControl_Table
{
    public void FunctionThatIsRunByFrameworkAutomatically()
    {
         // Do routine stuff that accesses UIControl_Table and makes copies of this and that

         // MODIFY THIS AND THAT WITH THE NEW STUFF I WANT IN THE UICONTROL            

         // Do  more routine stuff that belongs that accesses UIControl_Table and makes copies of this and that but passes in my modified stuff instead of the typical stuff the UI COntrol outputs
    }
}
4

1 回答 1

0

我认为,代理是您正在寻找的。代理文档中的一些示例代码:

为某些接口 Foo 创建代理:

 InvocationHandler handler = new MyInvocationHandler(...);
 Class proxyClass = Proxy.getProxyClass(
     Foo.class.getClassLoader(), new Class[] { Foo.class });
 Foo f = (Foo) proxyClass.
     getConstructor(new Class[] { InvocationHandler.class }).
     newInstance(new Object[] { handler });

或更简单地说:

  Foo f = (Foo) Proxy.newProxyInstance(Foo.class.getClassLoader(),
                                      new Class[] { Foo.class },
                                      handler);

更新:

我刚刚看到,Proxy 类只代理接口,但似乎不能扩展类。

于 2013-07-19T16:25:11.223 回答