首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Java元编程

Java元编程
EN

Stack Overflow用户
提问于 2012-01-15 15:03:13
回答 1查看 7.8K关注 0票数 13

我正在做我的第一个真正的Java项目。我开始适应这种语言,尽管我对动态语言有更多的经验。

我有一个类,它的行为类似于以下代码:

代码语言:javascript
复制
class Single
{
    public void doActionA() {}
    public void doActionB() {}
    public void doActionC() {}
}

然后我有一个SingleList类,它充当这些类的集合(具体地说,它用于2D Sprite库,“动作”是所有类型的转换:旋转、剪切、缩放等)。我希望能够做到以下几点:

代码语言:javascript
复制
class SingleList
{
    public void doActionA() {
        for (Single s : _innerList) {
            s.doActionA();
        }
    }

    ... etc ...
}

有没有办法简单地将一个方法(或已知的方法列表)推迟到内部列表的每个成员?有没有办法不专门列出每个方法,然后遍历每个内部成员并手动应用它?

让事情变得更难的是,这些方法的大小各不相同,但都是返回类型"void“。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-01-15 17:45:36

不幸的是,Java不支持在运行时创建类,而这正是您需要的:为了匹配Single类,需要使用必要的存根方法自动更新SingleList

我可以想到以下方法来解决这个问题:

使用Java reflection

代码语言:javascript
复制
- Pros:   
    - It's readily available in the Java language and you can easily find documentation and examples.

代码语言:javascript
复制
- Cons:  
    - The `SingleList` class would not be compatible with the `Single` class interface any more.
    - The Java compiler and any IDEs are typically unable to help with methods called via reflection - errors that would be caught by the compiler are typically transformed into runtime exceptions.
    - Depending of your use case, you might also see a noticeable performance degradation.

  1. 使用构建系统和某种源代码生成器自动创建SingleList.java文件。

代码语言:javascript
复制
- Pros:   
    - Once you set it up you will not have to deal with it any more.

代码语言:javascript
复制
- Cons:  
    - Setting this up has a degree of difficulty.
    - You would have to separately ensure that the `SingleList` class loaded in any JVM - or your IDE, for that matter - actually matches the loaded `Single` class.

  1. 手动解决了这个问题-创建一个接口(例如SingleInterface)或一个基础抽象类以供这两个类使用应该会有所帮助,因为任何像样的集成开发环境都会指出未实现的方法。正确的类体系结构将最大限度地减少重复代码,并且您的集成开发环境也许能够帮助生成样板部分。

代码语言:javascript
复制
- Pros:  
    - There is no setup curve to get over.
    - Your IDE will always see the right set of classes.
    - The class architecture is usually improved afterwards.

代码语言:javascript
复制
- Cons:  
    - Everything is manual.

  1. 使用字节码生成库(如JavassistBCEL )动态生成/修改SingleList类。

代码语言:javascript
复制
- Pros:   
    - This method is extremely powerful and can save a lot of time in the long term.

代码语言:javascript
复制
- Cons:  
    - Using bytecode generation libraries is typically _not_ trivial and _not_ for the faint-hearted.
    - Depending on how you write your code, you may also have issues with your IDE and its handling of the dynamic classes.

票数 13
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8868102

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档