我正在做我的第一个真正的Java项目。我开始适应这种语言,尽管我对动态语言有更多的经验。
我有一个类,它的行为类似于以下代码:
class Single
{
public void doActionA() {}
public void doActionB() {}
public void doActionC() {}
}然后我有一个SingleList类,它充当这些类的集合(具体地说,它用于2D Sprite库,“动作”是所有类型的转换:旋转、剪切、缩放等)。我希望能够做到以下几点:
class SingleList
{
public void doActionA() {
for (Single s : _innerList) {
s.doActionA();
}
}
... etc ...
}有没有办法简单地将一个方法(或已知的方法列表)推迟到内部列表的每个成员?有没有办法不专门列出每个方法,然后遍历每个内部成员并手动应用它?
让事情变得更难的是,这些方法的大小各不相同,但都是返回类型"void“。
发布于 2012-01-15 17:45:36
不幸的是,Java不支持在运行时创建类,而这正是您需要的:为了匹配Single类,需要使用必要的存根方法自动更新SingleList。
我可以想到以下方法来解决这个问题:
使用Java reflection的
- Pros:
- It's readily available in the Java language and you can easily find documentation and examples.
- 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.
SingleList.java文件。- Pros:
- Once you set it up you will not have to deal with it any more.
- 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.
SingleInterface)或一个基础抽象类以供这两个类使用应该会有所帮助,因为任何像样的集成开发环境都会指出未实现的方法。正确的类体系结构将最大限度地减少重复代码,并且您的集成开发环境也许能够帮助生成样板部分。- 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.
- Cons:
- Everything is manual.
SingleList类。- Pros:
- This method is extremely powerful and can save a lot of time in the long term.
- 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.
https://stackoverflow.com/questions/8868102
复制相似问题