【问题标题】:Creating a templating function that passes in a name for a class创建一个传入类名的模板函数
【发布时间】:2013-07-19 00:26:30
【问题描述】:

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

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

【问题讨论】:

  • 将问题标记为 Java 是表明这是一个 Java 问题的最佳标志,无需在第一行添加标题 也不再你的问题。
  • 你可以用泛型制作你的模板类
  • 您要解决的问题是什么?扩展类应该建模什么,回调函数要做什么?

标签: java class templates extend


【解决方案1】:

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

为某个接口 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 类只代理接口,但似乎不能扩展类。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-30
    • 2013-09-23
    相关资源
    最近更新 更多